基于自定义函数按键合并字典值

2024-10-03 15:24:28 发布

您现在位置:Python中文网/ 问答频道 /正文

假设您有两个字典,并且希望通过对具有匹配键的值应用函数来合并这两个字典。这里我使用+操作符作为二进制函数。你知道吗

x = { 1: "a", 2: "b", 3: "c" }
y = { 1: "A", 2: "B", 3: "C" }

result = { t[0][0]: t[0][1] + t[1][1] for t in zip(sorted(x.items()), sorted(y.items())) }

print result # gives { 1: "aA", 2: "bB", 3: "cC" }

我更喜欢自足的表达而不是陈述,但这是不可读的。你知道吗

到目前为止我在做:

def dzip(f, a, b):
    least_keys = set.intersection(set(a.keys()), set(b.keys()))
    copy_dict = dict()
    for i in least_keys.keys():
        copy_dict[i] = f(a[i], b[i])
    return copy_dict

print dzip(lambda a,b: a+b,x,y)

有没有比我给出的表达更具可读性的解决方案?你知道吗


Tags: 函数infor字典二进制itemsresultkeys
2条回答

在第一种情况下,您可以直接使用听写理解:

>>> x = { 1: "a", 2: "b", 3: "c" }
>>> y = { 1: "A", 2: "B", 3: "C" }
>>> {key: x.get(key, "") + y.get(key, "") for key in set.intersection(set(x.keys()), set(y.keys()))}
{1: 'aA', 2: 'bB', 3: 'cC'}

因此,在第二段代码中,您可以将其简化为简单的一行:

def dzip(f, a, b):
    return {key: f(a.get(key, ""), b.get(key, "")) for key in set.inersection(set(a.keys()) + set(b.keys()))}

您甚至可以将dzip定义为lambda:

dzip = lambda f, a, b: {key: f(a.get(key, ""), b.get(key, "")) 
    for key in set.intersection(set(a.keys()), set(b.keys()))}

在一次运行中,这将变成:

>>> dzip = lambda f, a, b: {key: f(a.get(key, ""), b.get(key, "")) 
...         for key in set.intersection(set(a.keys()), set(b.keys()))}    
>>> 
>>> print dzip(lambda a,b: a+b,x,y)
{1: 'aA', 2: 'bB', 3: 'cC'}

请注意,即使x和y有不同的键集(这可能会破坏您的第一个版本的代码)。你知道吗

您可以使用Counter进行这种类型的dict合并

from collections import Counter
>>>Counter(x)+Counter(y)
Counter({3: 'cC', 2: 'bB', 1: 'aA'})

相关问题 更多 >