python - 如何返回在不同字典中获得新值的字典键的值
问题描述
但是在我的情况下,我有两个字典
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
这个想法行不通,而且显然效率很低。我希望有一种更有效的工作方式来做到这一点
解决方案
两个 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']}
推荐阅读
- python - MDS 中的 const 初始向量
- sql - 如何在 SELECT 查询中设置条件限制?
- python - 将值的平均值写入 Pandas 数据框中的新列
- javascript - Wavesurfer 在循环 laravel 内不产生超过一次
- docusignapi - DocuSign API:自动放置(锚标记)不起作用
- excel - Excel SUMPRODUCT 忽略空白单元格或文本
- java - IOException:Broken pipe在spring MVC中随机出现错误
- python - 如何强制我的计算机使用不同的 python 版本?
- powershell - Powershell - 从数组中的每个字符串中获取变量
- html - 固定导航栏位于垂直滚动浏览器侧边栏的顶部