如何返回已在其他字典中获得新值的字典键的值

时间:2018-11-15 02:17:46

标签: python dictionary

我的问题有点类似于:Replacing the value of a Python dictionary with the value of another dictionary that matches the other dictionaries key

但是我有两个字典

dict1 = {'foo' : ['val1' , 'val2' , 'val3'] , 'bar' : ['val4' , 'val5']}

dict2 = {'foo' : ['val2', 'val10', 'val11'] , 'bar' : ['val1' , 'val4']}

我要退货的是

dict3 = {'foo' : ['val10', 'val11'] , 'bar' : ['val1']}

与之相反的是

dict4 = {'foo' : ['val1', 'val3'] , 'bar' : ['val5']}

其中dict3返回在dict2中获得键'foo'和'bar'的值的字典,而dict4是在dict2中丢失键'foo'和'bar'的值的字典

我尝试解决此问题的一种方法是:

 iterate over both dictionaries then
    if key of dict1 == key of dict2
       return the values of the key in dict1 and compare with the values in dict2
       return the values that aren't in both 
       as a dictionary of the key and those values

这个想法行不通,效率很低。我希望有一种更有效的工作方式来做到这一点

1 个答案:

答案 0 :(得分:3)

两个dict理解将达到目的:

dict3 = {k: [x for x in v if x not in dict1[k]] for k, v in dict2.items()}
print(dict3)
# {'foo': ['val10', 'val11'], 'bar': ['val1']}

dict4 = {k: [x for x in v if x not in dict2[k]] for k, v in dict1.items()}
print(dict4)
# {'foo': ['val1', 'val3'], 'bar': ['val5']}

以上两个理解基本上从另一个字典中不存在的键中筛选出值,这是双向完成的。

您也可以在没有 格理解的情况下执行此操作:

dict3 = {}
for k,v in dict2.items():
    dict3[k] = [x for x in v if x not in dict1[k]]

print(dict3)
# {'foo': ['val10', 'val11'], 'bar': ['val1']}

dict4 = {}
for k,v in dict1.items():
    dict4[k] = [x for x in v if x not in dict2[k]]

print(dict4)
# {'foo': ['val1', 'val3'], 'bar': ['val5']}