2017-02-25 76 views
0

如果我有我從不同規模合併兩個大小不同的詞典和不同的價值觀

dictionary1: 
{'id': 1 , 'passCount': 3}, {'id': 2 , 'passCount': 4}, {'id': 5 , 'passCount': 7}, {'id': 6, 'passCount': 3} 

dictionary2: 
{'id': 1 , 'failCount': 1}, {'id': 3 , 'failCount': 2}, {'id': 5 , 'failCount': 3} 

最初的查詢創建了兩個不同的字典,我創建這兩個字典的主列表:

List = [] 
for i in dictionary1: 
for j in dictionary2: 
    if i['id'] = j['id]: 
     List.append[i['id'],i['passCount'],j['failCount']] 
    else: 
     List.append[i['id'],i['passCount'],0] 
     List.append[j['id'],0, j['failCount'] 
return List 

當我將這個列表打印出來用於我的數據時,我只會得到一個匹配的id列表,而不會考慮其他列表。

出於這個原因,我想打印一本字典在那裏我​​能得到它的打印

{'id' = 1, 'passCount' = 3, 'failCount' = 1}, {'id': 2 , 'passCount': 4, 'failCount' = 0}...等,但不刪除任何標識的

致謝

+0

結構含有'dictionary1','dictionary2'無效 – RomanPerekhrest

回答

0

短溶液使用dict.setdefaultdict.update方法:

l1 = [{'id': 1 , 'passCount': 3}, {'id': 2 , 'passCount': 4}, {'id': 5 , 'passCount': 7}, {'id': 6, 'passCount': 3}] 
l2 = [{'id': 1 , 'failCount': 1}, {'id': 3 , 'failCount': 2}, {'id': 5 , 'failCount': 3}] 

grouped = {} 
for d in l1+l2: 
    grouped.setdefault(d['id'], {'failCount':0, 'passCount': 0}).update(d) 

result = [d for d in grouped.values()] 
print(result) 

輸出:

[{'passCount': 3, 'id': 1, 'failCount': 1}, {'passCount': 4, 'id': 2, 'failCount': 0}, {'passCount': 0, 'id': 3, 'failCount': 2}, {'passCount': 7, 'id': 5, 'failCount': 3}, {'passCount': 3, 'id': 6, 'failCount': 0}] 
+0

唯一不幸的部分是'id':3,'passCount'應該是'passCount'= 0而不是沒有它 – Draklin

+0

@Draklin,沒問題,看我的更新 – RomanPerekhrest

+0

非常感謝!工作就像一個魅力 – Draklin

0

也許他們是兩個不同的列表,而不是字典,所以我假設他們是兩個列表:

默認設置爲0,您可以試試這個:

a=[{'id': 1 , 'passCount': 3}, {'id': 2 , 'passCount': 4}, {'id': 5 , 'passCount': 7}, {'id': 6, 'passCount': 3}] 
b=[{'id': 1 , 'failCount': 1}, {'id': 3 , 'failCount': 2}, {'id': 5 , 'failCount': 3}] 

for j in a: 
    j.update({'failCount': 0}) 
    for i in b: 
     if i["id"]==j["id"]: 
      j.update(i) 

print(a) 

輸出:

[{'id': 1, 'passCount': 3, 'failCount': 1}, {'id': 2, 'passCount': 4, 'failCount': 0}, {'id': 5, 'passCount': 7, 'failCount': 3}, {'id': 6, 'passCount': 3, 'failCount': 0}] 
+0

讓我們說有沒有一個'failCount'的具體ID,任意設置爲0?並打印出 {'id':2,'passCount':4,'failCount':0} – Draklin