Python使用自定义合并函数合并字典 [英] Python merge dictionaries with custom merge function

查看:151
本文介绍了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}

这篇关于Python使用自定义合并函数合并字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆