To combine two dicts with overlapping keys

Asked 2 years ago, Updated 2 years ago, 119 views

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

2022-09-22 22:28

1 Answers

[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'}


2022-09-22 22:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.