[英]Python. How to merge two dictionaries with the same keys?
I have two dicts:我有两个字典:
a = {'a': 1, 'b': 2, 'c': 3}
b = {'a': 2, 'd': 4, 'c': 5}
and i want to get:我想得到:
{'a': 2, 'b': 2, 'c': 5}
i used {**a, **b} but it return:我使用了 {**a, **b} 但它返回:
{'a': 2, 'b': 2, 'c': 5, 'd': 4}
Help me please exclude keys from b which not in a with the simplest and fastest way.帮助我,请以最简单和最快的方式从 b 中排除不在 a 中的键。
i have python 3.7我有 python 3.7
You have to filter the elements of the second dict
first in order to not add any new elements.您必须先过滤第二个dict
的元素,以免添加任何新元素。 I got two possible solutions:我有两种可能的解决方案:
a = {'a': 1, 'b': 2, 'c': 3}
b = {'a': 2, 'd': 4, 'c': 5}
for k,v in b.items():
if (k in a.keys()):
a[k] = v
print(a)
a = {'a': 1, 'b': 2, 'c': 3}
b = {'a': 2, 'd': 4, 'c': 5}
a.update([(k,v) for k, v in b.items() if k in a.keys()])
print(a)
Output for both: Output 对于两者:
{'a': 2, 'b': 2, 'c': 5}
I think a comprehension is easy enough:我认为理解很容易:
{ i : (b[i] if i in b else a[i]) for i in a }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.