在Python中将字典加在一起

时间:2018-07-09 10:22:07

标签: python python-3.x dictionary counter

如果我有2个字典static final String KEY_ROWID = "_id"; static final String KEY_NAME = "name"; static final String KEY_INVOICE = "invoice"; static final String KEY_QUALITY ="quality"; static final String KEY_DATE ="date"; static final String KEY_PASSWORD="password"; static final String KEY_APPLICATION="application"; static final String TAG = "DBAdapter"; static final String DATABASE_NAME = "MyDB"; static final String DATABASE_TABLE = "contact"; static final int DATABASE_VERSION = 1; static final String DATABASE_CREATE = //---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } x={'a':1,'b':2}

我想要输出y={'a':1,'b':3},是否有z={'a':2,'b':5}函数,还是应该将两个字典都转换为数据帧,然后将它们与z=dict.add(x,y)一起添加?

3 个答案:

答案 0 :(得分:3)

在这种情况下,您可以使用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))

输出:

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

或使用 +

from pprint import pprint
from collections import Counter

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

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

答案 1 :(得分:1)

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}

答案 2 :(得分:0)

代码:

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)

输出:

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