Python merge dictionaries with custom merge function

前端 未结 8 1947
北海茫月
北海茫月 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:20

    Stealing this (A.get(k, B.get(k)) snippet from @MartijnPieters

    >>> def f(x, y):
            return x * y
    
    >>> A = {1:1, 2:3}
    >>> B = {7:3, 2:2}
    >>> {k: f(A[k], B[k]) if k in A and k in B else A.get(k, B.get(k))
         for k in A.viewkeys() | B.viewkeys()}
    {1: 1, 2: 6, 7: 3}
    

提交回复
热议问题