I’m working on a Python project where I need to merge two dictionaries, but I want to ensure that there are no duplicate keys as the end result should contain unique keys with their corresponding values. Here’s what I’ve tried:
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
This approach overwrites the value of duplicate keys, but I’m looking for a way to either prevent duplicates or handle them in a specific manner (e.g., by adding the values together or keeping the higher value).
I’ve searched for solutions, but most methods don’t address handling duplicates in the way I need. Is there an efficient Pythonic way to merge dictionaries while managing duplicates according to custom logic?
Environment: Python 3.8 on Ubuntu 20.04
3
Answers
This is a longer way to do this than some of the ways listed in the comments but here is a way you can do it:
The output will be:
If you want a max value instead of the sum just change ‘sum’ to ‘max’ and your output will be:
This seems straight forward enough.
giving you:
Here is my variant of the solution:
By doing a
|
operation we get a "pre-merged" dict which has values from bothd1
andd2
, withd2
taking priority. Then, in thefor
loop, we find keys which are present in both of dictionaries by leveraging set intersection operation, and overwrite those keys with values in the way we want.Or, if you would prefer a one-liner, here you go:
But it looks huge, personally I would prefer the first option