Python merge dictionaries with custom merge function

前端 未结 8 2037
北海茫月
北海茫月 2021-01-13 18:39

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

  • All pairs from A where key is unique to A
  • All pairs from B where key is unique
8条回答
  •  没有蜡笔的小新
    2021-01-13 19:21

    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
    

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

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

    Demo:

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

提交回复
热议问题