Python使用自定义合并功能合并词典 [英] Python merge dictionaries with custom merge function

查看:130
本文介绍了Python使用自定义合并功能合并词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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



  • 来自B的所有对,其中key对于B

  • f(valueA,valueB)是唯一的,其中A和B中都存在相同的键

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

感觉像应该有一个很好的一行来做这个。

It feels like there should be a nice one-liner to do this.

推荐答案

使用字典视图实现此目的; dict.viewkeys()结果的行为就像一组,让你做交集和对称差异:

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()功能(在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天全站免登陆