python dict.add_by_value(dict_2)? [英] python dict.add_by_value(dict_2)?

查看:140
本文介绍了python dict.add_by_value(dict_2)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

>>> a = dict(a=1,b=2    )
>>> b = dict(    b=3,c=2)

>>> c = ???

c = {'a': 1, 'b': 5, 'c': 2}

所以,这个想法是以最短的形式通过int / float值添加两个字典。
这是我设计的一个解决方案,但我不喜欢它,因为它很长:

So, the idea is two add to dictionaries by int/float values in the shortest form. Here's one solution that I've devised, but I don't like it, cause it's long:

c = dict([(i,a.get(i,0) + b.get(i,0)) for i in set(a.keys()+b.keys())])

我认为必须有一个较短/简明的解决方案(可能与reduce和operator module?itertools有关)?任何想法?

I think there must be a shorter/concise solution (maybe something to do with reduce and operator module? itertools?)... Any ideas?

更新:我真的希望找到像reduce(operator.add,key = itemgetter(0),a + b)。 (显然这不是真正的代码,但你应该得到这个想法)。但似乎可能是一个梦想。

Update: I'm really hoping to find something more elegant like "reduce(operator.add, key = itemgetter(0), a+b)". (Obviously that isn't real code, but you should get the idea). But it seems that may be a dream.

更新:仍然倾向于更简洁的解决方案。也许groupby可以帮忙吗?
我使用reduce/groupby提出的解决方案实际上并不简单:

Update: Still loking for more concise solutions. Maybe groupby can help? The solution I've come up with using "reduce"/"groupby" isn't actually concise:

from itertools import groupby
from operator import itemgetter,add

c = dict( [(i,reduce(add,map(itemgetter(1), v))) \
              for i,v in groupby(sorted(a.items()+b.items()), itemgetter(0))] )


推荐答案

解决不是长度而是表现,我会执行以下操作:

solving not in terms of "length" but performance, I'd do the following:

>>> from collections import defaultdict
>>> def d_sum(a, b):
        d = defaultdict(int, a)
        for k, v in b.items():
            d[k] += v
        return dict(d)
>>> a = {'a': 1, 'b': 2}
>>> b = {'c': 2, 'b': 3}
>>> d_sum(a, b)
{'a': 1, 'c': 2, 'b': 5}

它也是py3k兼容的,不像你的原始代码。

it's also py3k-compatible, unlike your original code.

这篇关于python dict.add_by_value(dict_2)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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