简体   繁体   English

合并具有最小公共密钥值的字典

[英]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? 如果没有,最优雅的方式是什么?

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 h1.viewkeys() | h2 actually finds the set union and gets all the keys which are either in h1 or h2 . h1.viewkeys() | h2实际上找到了set union并得到了所有在h1h2的键。 Then, we find the minimum value of the corresponding key from h1 and `h2. 然后,我们从h1和`h2找到相应键的最小值。

If you are using Python 3.x, then you just need to use keys , likie this 如果您使用的是Python 3.x,那么您只需要使用keys ,这样就可以了

>>> {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. 如果所有值都是可清除的,那么(键,值)对是唯一且可清除的,那么items视图也是类似于set。 (Values views are not treated as set-like since the entries are generally not unique.) (值视图不会被视为类似集合,因为条目通常不是唯一的。)

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM