Merge dictionaries with minimum value of common keys

Question:

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?

Asked By: nish

||

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, like this

>>> {k : min(i for i in (h1.get(k), h2.get(k)) if i is not None) 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.)

Answered By: thefourtheye

You can try this too:

>>> {k: min(h1.get(k) or h2[k], h2.get(k) or h1[k]) for k in (h1.keys() + h2.keys())} 
{'a': 1, 'c': 2, 'b': 5, 'd': 10}
Answered By: user4590566
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.