简体   繁体   English

Python。 如何合并具有相同键的两个字典?

[英]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.

相关问题 使用相同的键合并Python中的两个词典 - Merge two dictionaries in Python with the same keys 如何在python中合并两个具有相同键和数组类型值的嵌套字典? - How to merge two nested dictionaries in python, which have same keys and have array type values? 如何在不覆盖数据的情况下合并两个具有相同键的字典? - How to merge two dictionaries with the same keys without overwriting data? 如何将两个字典与同一列表中的不同键合并? - how to merge two dictionaries with different keys that are inside same list? 如何在python的相同键中合并具有多个值的字典 - How to merge dictionaries with many values in the same keys in python Python中如何合并两个具有共同和不同键的字典? - How To Merge Two Dictionaries With Common and Different Keys in Python? 如何在Python中根据两个字典的键和值合并? - How to merge two dictionaries based on their keys and values in Python? 将两个带有嵌套字典的字典合并为新字典,将相同的键求和并将未更改的键保留在Python中 - Merge two dictionaries with nested dictionaries into new one, summing same keys and keeping unaltered ones in Python Python 合并相同长度但不同键的字典 - Python Merge dictionaries of same length but different keys Python - 将两个词典合并为一个列表(按键) - Python - Merge two dictionaries into a single list (By Keys)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM