首页 > 解决方案 > 如何返回在不同字典中获得新值的字典键的值

问题描述

我的问题有点类似于:Replaceing the value of a Python dictionary with the value of another dictionary that match 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返回键'foo'和'bar'在dict2中获得的值的字典,dict4是键'foo'和'bar'在dict2中丢失的值的字典

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

 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

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

标签: pythondictionary

解决方案


两个 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']}

上面的两个推导基本上从 key 中过滤掉了另一个字典中不存在的值,这是双向的。

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

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']}

推荐阅读