Python使用自定义合并函数合并字典

问题描述:

我要合并两个字典A和B,以便结果包含:

I want to merge two dictionaries A and B such that the result contains:


  • 所有来自A的对,其中key是唯一的

  • 来自B的所有对,其中键是B的唯一

  • f(valueA,valueB) li>
  • All pairs from A where key is unique to A
  • All pairs from B where key is unique to B
  • f(valueA, valueB) where the same key exists in both A and B

例如:

def f(x, y):
    return x * y

A = {1:1, 2:3}
B = {7:3, 2:2}

C = merge(A, B)

输出:

{1:1, 7:3, 2:6}

感觉像是一个很好的单线程>使用字典视图实现此目的; dict.viewkeys() result 像一个集合,让你做交叉和对称的差异:

Use dictionary views to achieve this; the dict.viewkeys() result acts like a set and let you do intersections and symmetrical differences:

def merge(A, B, f):
    # Start with symmetric difference; keys either in A or B, but not both
    merged = {k: A.get(k, B.get(k)) for k in A.viewkeys() ^ B.viewkeys()}
    # Update with `f()` applied to the intersection
    merged.update({k: f(A[k], B[k]) for k in A.viewkeys() & B.viewkeys()})
    return merged



在Python 3中,。 viewkeys()方法已重命名为 .keys(),替换旧的 .keys $ c> function(在Python 2中返回一个列表)。

In Python 3, the .viewkeys() method has been renamed to .keys(), replacing the old .keys() functionality (which in Python 2 returs a list).

上面的 merge()通用解决方案适用于任何给定的 f()

The above merge() method is the generic solution which works for any given f().

演示:

>>> def f(x, y):
...     return x * y
... 
>>> A = {1:1, 2:3}
>>> B = {7:3, 2:2}
>>> merge(A, B, f)
{1: 1, 2: 6, 7: 3}
>>> merge(A, B, lambda a, b: '{} merged with {}'.format(a, b))
{1: 1, 2: '3 merged with 2', 7: 3}