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

Merge dictionaries with minimum value of common keys

我有两本字典。我想合并这些字典,使得结果字典中任何键的值都是用于合并的两个字典中键值的最小值。

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}

有没有酷炫的眼线笔呢?如果不是,最优雅的方法是什么?

你可以这样做

>>> {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 实际上找到了集合并集并获取了 h1h2 中的所有键。然后,我们从 h1 和 `h2.

中找到对应键的最小值

如果你正在使用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}

注意:上面显示的类似集合的操作是有效的,因为它们确实是类似集合的。引用 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.)

你也可以试试这个:

>>> {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}