简体   繁体   English

在Python中将字典加在一起

[英]Adding dictionaries together in Python

If i have 2 dictionaries x={'a':1,'b':2} and y={'a':1,'b':3} 如果我有2个字典x={'a':1,'b':2}y={'a':1,'b':3}

and i want the output z={'a':2,'b':5} , is there a z=dict.add(x,y) function or should i convert both dictionaries into dataframes and then add them together with z=x.add(y) ? 我想要输出z={'a':2,'b':5} ,是否有z=dict.add(x,y)函数,还是应该将两个字典都转换为数据框,然后将它们与z=x.add(y)一起添加z=x.add(y)吗?

You could use Counter in this case for example: 例如,您可以在这种情况下使用Counter

from pprint import pprint
from collections import Counter

x={'a':1,'b':2}
y={'a':1,'b':3}

c = Counter()
c.update(x)
c.update(y)

pprint(dict(c))

Output: 输出:

{'a': 2, 'b': 5}

Or using + : 或使用+

from pprint import pprint
from collections import Counter

x={'a':1,'b':2}
y={'a':1,'b':3}

pprint(dict(Counter(x) + Counter(y)))

collections.Counter is the natural method, but you can also use a dictionary comprehension after calculating the union of your dictionary keys: collections.Counter是自然的方法,但是您也可以在计算字典键的并集之后使用字典理解:

x = {'a':1, 'b':2}
y = {'a':1, 'b':3}

dict_tup = (x, y)

keys = set().union(*dict_tup)
z = {k: sum(i.get(k, 0) for i in dict_tup) for k in keys}

print(z)

{'a': 2, 'b': 5}

Code: 码:

from collections import Counter

x = {"a":1, "b":2}
y = {"a":1, "b":3}

c = Counter(x)
c += Counter(y)
z = dict(c)
print(z)

Output: 输出:

{'a': 2, 'b': 5}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM