2
dict1 = {'a': 10, 'b': 8, 'c':5} 
dict2 = {'d': 6, 'c': 4, 'a':20}

Given two dictionaries, I'd like an output of.

output = {'a':30, 'b':8, 'c':9, 'd':6}

This is what I've so far, not quite sure what I'd do next. I'm looking for a solution that is efficient in time/space complexity.

def merge_dict(dict1, dict2):
    merged_dictionaries = {**dict1, **dict2} 
    return merged_dictionaries



dict1 = {'a': 10, 'b': 8, 'c':5} 
dict2 = {'d': 6, 'c': 4, 'a':20}


merge_dictionaries = merge_dict (dict1, dict2)
sorted_dictionary = sorted(merge_dictionaries)

4 Answers4

3

If the values are numeric, you can use counters:

from collections import Counter

def merge_dicts(*dicts):
    return dict(sum(map(Counter, dicts), Counter()))


dict1 = merge_dicts(dict1, dict2)
dict1

# {'a': 30, 'b': 8, 'c': 9, 'd': 6}

This might be a bit excessive for only two dictionaries, so another option is:

for k, v in dict2.items():
    dict1[k] = dict1.setdefault(k, 0) + v

dict1
# {'a': 30, 'b': 8, 'c': 9, 'd': 6}

Which updates dict1 in-place.

Finally, if you really need the result sorted (python3.7+), use

result = {k : dict1[k] for k in sorted(dict1)}
cs95
  • 379,657
  • 97
  • 704
  • 746
1

You can use a dict comprehension that iterates over a sorted union of the keys of the two dicts, and outputs values that are sums of the respective values of two dicts by the given keys, defaulting to 0:

{k: dict1.get(k, 0) + dict2.get(k, 0) for k in sorted(dict1.keys() | dict2.keys())}

This returns:

{'a': 30, 'b': 8, 'c': 9, 'd': 6}
blhsing
  • 91,368
  • 6
  • 71
  • 106
0
result = dict(Counter(dict1) + Counter(dict2))
result = {k: result[k] for k in sorted(result)}     

First merge the dicts together by turning them into Counters and convert the result it back into a dict, then sort the dict by keys.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
0

You can Try Collections for add two dictionary..

from collections import Counter
def merged_dic():
    dict1 = {'a': 10, 'b': 8, 'c':5} 
    dict2 = {'d': 6, 'c': 4, 'a':20}
    a = Counter(dict1)
    b = Counter(dict2)
    c = a+b
    print(dict(c))

merged_dic()

Output:- {'a': 30, 'b': 8, 'c': 9, 'd': 6}