If there are overlapping keys when combining two dict
, I would like to add a value corresponding to the key.
For example, if you have the following A
and B
Dict A: {'a':1, 'b':2, 'c':3}
Dict B: {'b':3, 'c':4, 'd':5}
Combining the two dict
{'a':1, 'b':5, 'c':7, 'd':5}
A function with the same result is required.
Which one is the most Python-like?
python dictionary
[collections.Counter] is a subclass of dict
Save the count values of key
and key
as a key-value
pair.
*However, it can only be written if value
in dict
is a number.
from collections import Counter
A = Counter({'a':1, 'b':2, 'c':3})
B = Counter({'b':3, 'c':4, 'd':5})
print(A + B)
Result: Counter({'c':7,'b':5,'d':5,'a':1})
a = {'a': 'foo', 'b':'bar', 'c': 'baz'}
b = {'a': 'spam', 'c':'ham', 'x': 'blah'}
r = dict(a.items() + b.items() +
[(k, a[k] + b[k]) for k in set(b) & set(a)])
import operator
def combine_dicts(a,b,op=operator.add):#supports addition (add), multiplication (mul), division (div), etc
return dict(a.items() + b.items() +
[(k, op(a[k], b[k])) for k in set(b) & set(a)])
a = {'a': 'foo', 'b':'bar', 'c': 'baz'}
b = {'a': 'spam', 'c':'ham', 'x': 'blah'}
print(combine_dicts(a,b))
Results: {'a': foospam', 'x': 'blah', 'c': 'bazham', 'b': 'bar'}
© 2024 OneMinuteCode. All rights reserved.