Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge dictionaries with minimum value of common keys

I have two dictionaries. I want to merge these dictionaries such that the value for any key in the resultant dictionary is the minimum of the values for the key in the two dictionaries used to merge.

h1 = {"a":3, "b":5, "c":2}
h2 = {"a":1, "c":5, "d":10}

result = merge(h1, h2) = {"a":1, "b":5, "c":2, "d":10}

Is there a cool one liner do so? If not, what is the most elegant way of doing this?

like image 713
nish Avatar asked Feb 21 '15 05:02

nish


People also ask

Can I merge two dictionaries Python?

In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.

Which function helps to merge dictionary d1 and d2 merge append update get?

Using deepcopy() and dict. If we don't want to update the original dictionary means, we can create a copy of the dictionary and update it. To merge two dictionaries d1 and d2, create deepcopy(d1) as d and then do the update method. In this way, the original dictionary will not be modified.


1 Answers

You can do it like this

>>> {k: min(i for i in (h1.get(k), h2.get(k)) if i) for k in h1.viewkeys() | h2}
{'a': 1, 'c': 2, 'b': 5, 'd': 10}

h1.viewkeys() | h2 actually finds the set union and gets all the keys which are either in h1 or h2. Then, we find the minimum value of the corresponding key from h1 and `h2.

If you are using Python 3.x, then you just need to use keys, likie this

>>> {k : min(i for i in (h1.get(k), h2.get(k)) if i) for k in h1.keys() | h2}
{'d': 10, 'a': 1, 'b': 5, 'c': 2}

Note: The above shown set like operations are working, because they really are set-like. Quoting the official documentation,

Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. (Values views are not treated as set-like since the entries are generally not unique.)

like image 195
thefourtheye Avatar answered Oct 20 '22 17:10

thefourtheye