Merge 2 dictionaries with higher value for each key

Viewed 78

I have

dict1 = {a: 1, b: 2, c: 3}
dict2 = {b: 3, c: 2}

How do I merge dict1 and dict2 so that the result dict3 will have {a: 1, b: 3, c: 3} I know we can merge like this dict3 = {**a, **b}, but is there a condition anywhere I have to write to make it work for my problem?

3 Answers

Here you go:

dict1 = {"a": 1, "b": 2, "c": 3}
dict2 = {"b": 3, "c": 2}

result = {}
for k in dict1.keys() | dict2.keys():
    result[k] = max(dict1.get(k, float('-inf')), dict2.get(k,float('-inf')))

print(result)

I am using a get with default: dict1.get(k, DEFAULT) and joining the two keysets with the bitwise OR operator |.

Note that the default of float('-inf') means the result for

dict1 = {"a": -1, "b": 2, "c": 3}
dict2 = {"b": -5, "c": 2}```

becomes {'a': -1, 'b': 2, 'c': 3}.

While for the default of 0 you would get {'b': 2, 'c': 3, 'a': 0}

Both ways could be considered equally valid responses.

You can merge the dict items into one sequence of tuples, sort them, and then use the dict constructor to create a new dict from the sorted sequence so that items of the same keys but with higher values will override those with lower values:

dict(sorted((*dict1.items(), *dict2.items())))

You could simply loop through them and compare the values, and use dict.setdefault(key, 0) to get around unset values.

dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 3, 'c': 2}

dict3 = {}
for d in dict1, dict2:
    for k, v in d.items():
        if v > dict3.setdefault(k, 0):
            dict3[k] = v
print(dict3)  # -> {'a': 1, 'b': 3, 'c': 3}

defaultdict(int) would also work but I wanted to avoid the import.

Related