簡體   English   中英

將值添加到字典中的某些鍵?

[英]Adding values to certain keys in a dictionary?

我有一個數據集,它目前是一個像這樣的字典:

["Test Suite #1"], ["unnecessary info"], ["tc1"], ["tc2"], ["tc3"], ["unnecessary info"], 
 ["Test Suite #2"], ["unnecessary info"], ["tc4"], ["tc5"], ["tc6"], ["unnecessary info"] 

我想從這個數據集中提取“測試套件#”(所以是關鍵)和來自該測試套件的必要數據(所有帶有“tc”的項目)。 所以我所做的是有一些 for 循環來遍歷數據:

for key, value in data.items(): 
    new_data_set = {}
    new_data_set.update({key: ''})
    for items in value: 
        if tc_flag in items:        #this flag basically looks for items with tc
          new_dict.update({key:items})

這會產生以下輸出:

{Test Suite#1: [tc1], Test Suite#2: [tc4]} 

但我想產生這樣的輸出:

{Test Suite#1: [tc1], [tc2], [tc3], Test Suite#2: [tc4], [tc5], [tc6]}

我怎么能做到這一點?

你想要,作為值,作為列表,你需要附加每個元素,而不是替換前一個元素,在每次迭代時制作一個列表以保留你需要的東西

data = {"Test Suite  # 1": ["unnecessary info", "tc1", "tc2", "tc3", "unnecessary info"],
        "Test Suite  # 2": ["unnecessary info", "tc4", "tc5", "tc6", "unnecessary info"]}
new_dict = {}
tc_flag = "tc"
for key, value in data.items():
    keep_values = []
    for items in value:
        if tc_flag in items:  # this flag basically looks for items with tc
            keep_values.append(items)
    new_dict[key] = keep_values

print(json.dumps(new_dict))  # {"Test Suite  # 1": ["tc1", "tc2", "tc3"], "Test Suite  # 2": ["tc4", "tc5", "tc6"]}

這可以通過defaultdict自動使用您提供的值來完成,這里是一個list

new_dict = defaultdict(list)
for key, value in data.items():
    for items in value:
        if tc_flag in items:  
            new_dict[key].append(items)

您可以使用 dict-comprehension 縮短此時間

new_dict = {
    key: [item for item in values if tc_flag in item]
    for key, values in data.items()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM