加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在python中对嵌套字典值求和

发布时间:2020-12-20 11:27:23 所属栏目:Python 来源:网络整理
导读:我有这样的字典, data={11L: [{'a': 2,'b': 1},{'a': 2,'b': 3}],22L: [{'a': 3,'b': 2},'b': 5},{'a': 4,{'a': 1,'b': 0}],33L: [{'a': 1,{'a': 3,{'a': 5,'b': 3},'b': 6},{'a':2,'b':0}],44L: [{'a': 4,{'a':1,'b':2},'b': 0}]} 在这里我将摆脱外键,并给
我有这样的字典,

data={11L: [{'a': 2,'b': 1},{'a': 2,'b': 3}],22L: [{'a': 3,'b': 2},'b': 5},{'a': 4,{'a': 1,'b': 0}],33L: [{'a': 1,{'a': 3,{'a': 5,'b': 3},'b': 6},{'a':2,'b':0}],44L: [{'a': 4,{'a':1,'b':2},'b': 0}]}

在这里我将摆脱外键,并给出新的键值1,2,3等,我想得到如下所示的结果,

result={1:{'a':10,'b':7},2:{'a':11,'b':18},3:{'a':12,'b':5},4:{'a':5,'b':11},5:{'a':3,'b':9},6:{'a':3,7:{'a':1,'b':0}}

我试过这样的事情,但我得到了所需的结果,

d = defaultdict(int)
for dct in data.values():
  for k,v in dct.items():
    d[k] += v
print dict(d)

我希望结果字典的键是动态的,就像在上面的数据字典中我们有44个最高的7个键值对,因此我们有7个键的结果字典等等

解决方法

你想在这里使用一个列表,你想要使用Counter()对象来使得求和更容易:

from collections import Counter
from itertools import izip_longest

for dcts in data.values():
    for i,dct in enumerate(dcts):
        if i >= len(result):
            result.append(Counter(dct))
        else:
            result[i].update(dct)

结果:

>>> result
[Counter({'a': 10,'b': 7}),Counter({'b': 18,'a': 11}),Counter({'a': 12,'b': 5}),Counter({'b': 11,'a': 5}),Counter({'b': 9,'a': 4}),Counter({'a': 3,'b': 2}),Counter({'a': 1,'b': 0})]

Counter()对象是dict的子类,因此它们表现为字典.如果之后必须有dict值,请添加以下行:

result = [dict(r) for r in result]

从Eric那里获取灵感,您可以将上述内容转化为单行:

from collections import Counter
from itertools import izip_longest

result = [sum(map(Counter,col),Counter()) 
    for col in izip_longest(*data.values(),fillvalue={})]

这个版本与上面的循环略有不同,因为在求和时从计数器中删除了0的键.如果你想在最后一个计数器中保持’b’:0,请使用:

[reduce(lambda c,d: c.update(d) or c,col,Counter())
    for col in izip_longest(*data.values(),fillvalue={})]

这再次使用.update().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读