2016-10-08 87 views
0

我有兩個字典我如何比較2個字典?

dict_a = {'x' : 2, 'y' : 3.5, 'z' : 4} 
dict_b = {'bob' : ['x', 'y'], 'john' : ['z', 'x'], 'bill' : ['y']} 

我想比較兩個庫和dict_a創建一個新的與dict_b鍵和值如果值從dict_b比賽。我希望看到:

new_dict = {'bob' : [2, 3.5], 'john' : [4, 2], 'bill' : [3.5]} 

我曾嘗試下面的代碼:

for name, guess in dict_b.items(): 
    if guess == i in dict_a.values(): 
     new_dict[name].append(i) 
print(new_dict) 

我得到的錯誤NameError: name 'i' is not defined,但我不知道如何定義「我」。

感謝所有幫助

回答

1

這可以用一個簡單的字典理解來完成:

>>> {k: [dict_a.get(x,x) for x in v] for k, v in dict_b.items()} 
{'bob': [2, 3.5], 'john': [4, 2], 'bill': [3.5]} 

這與那些從dict_a如果存在替代值。否則,請保留dict_b.get(x,x)中的第二個參數)。

另外,修復原有的代碼是這樣的:

new_dict = {} 
for name, guess in dict_b.items(): 
    new_dict[name] = [] 
    for value in guess: 
     if value in dict_a: 
      new_dict[name].append(dict_a[value]) 
print(new_dict) 
3

以及像這樣:

new_dict = {name: [dict_a[k] for k in dict_b[name]] for name in` dict_b.keys()} 
2
if guess == i in dict_a.values(): 

這不會做你希望它做什麼。這裏的Python連鎖運營商,所以你的測試等同於以下內容:

(guess == i) and (i in dict_a.values()) 

所以它不喜歡的for循環在這裏執行,你遍歷字典中的值的變量i

此外,你實際上需要從那些多個鍵收集值,所以你會想在這裏做的是以下幾點:

new_dict = {} 
for name, guesses in dict_b.items(): 
    result = [] 
    for guess in guesses: 
     if guess in dict_a: 
      result.append(dict_a[guess]) 
    new_dict[name] = result 

然後,你也可以使用列表解析來縮短這個:

new_dict = {} 
for name, guesses in dict_b.items(): 
    new_dict[name] = [dict_a[guess] for guess in guesses if guess in dict_a] 

最後,你甚至可以用字典的理解結合本:

new_dict = { name: [dict_a[guess] for guess in guesses if guess in dict_a] for name, guesses in dict_b.items() }