Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Adding" Dictionaries in Python? [duplicate]

People also ask

Can dictionaries in Python have duplicates?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Do dictionaries allow duplicates?

[C#] Dictionary with duplicate keys The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

Can dictionaries be added in Python?

Python dictionary is one of the built-in data types. Dictionary elements are key-value pairs. You can add to dictionary in Python using multiple methods.


How about that:

dict( [ (n, a.get(n, 0)+b.get(n, 0)) for n in set(a)|set(b) ] )

Or without creating an intermediate list (generator is enough):

dict( (n, a.get(n, 0)+b.get(n, 0)) for n in set(a)|set(b) )

Post Scriptum:

As a commentator addressed correctly, there is a way to implement that easier with the new (from Py2.7) collections.Counter class. As much I remember, this version was not available when I wrote the answer:

from collections import Counter
dict(Counter(a)+Counter(b))

Not in one line, but ...

import itertools
import collections
a = dict()
a['cat'] = 1
a['fish'] = 10
a['aardvark'] = 1000
b = dict()
b['cat'] = 2
b['dog'] = 200
b['aardvark'] = 2000
c = collections.defaultdict(int)
for k, v in itertools.chain(a.iteritems(), b.iteritems()):
    c[k] += v

You can easily extend it to a larger number of dictionaries.


result in a:

for elem in b:
    a[elem] = a.get(elem, 0) + b[elem]

result in c:

c = dict(a)
for elem in b:
    c[elem] = a.get(elem, 0) + b[elem]

One liner (as sortof requested): get key lists, add them, discard duplicates, iterate over result with list comprehension, return (key,value) pairs for the sum if the key is in both dicts, or just the individual values if not. Wrap in dict.

>>> dict([(x,a[x]+b[x]) if (x in a and x in b) else (x,a[x]) if (x in a) else (x,b[x]) for x in set(a.keys()+b.keys())])
{'aardvark': 3000, 'fish': 10, 'dog': 200, 'cat': 3}