如何将嵌套dicts的列表与其值中的公用键相加?

时间:2018-04-20 01:31:24

标签: python

我怎样才能列出这样的词组:

ps = [{'one': {'a': 30,
               "b": 30},
       'two': {'a': -1000}},
      {'three': {'a': 44}, 'one': {'a': -225}},
      {'one': {'a': 2000,
               "b": 30}}]

并制作一个像这样的词典:

{"one": {"a": 1805, "b": 60}, "two": {"a": -1000}, "three": {"a": 44}}

我很确定我可以使用collections.Counter()来做到这一点,但到目前为止我所做的并不起作用。它只返回ab的最后一个值为每个元素:

res = Counter(ps[0])
for t in ps[1:]:
    for key, vals in t.items():
        res.update(vals)
        if key not in res.keys():
            res[key] = vals
        else:
            res[key].update(vals)

# Wrong!
res
Counter({'one': {'a': 2000, 'b': 30}, 'two': {'a': -1000}, 'a': 1819, 'b': 30})

我是python的新手,所以请原谅我确定的丑陋代码。

1 个答案:

答案 0 :(得分:0)

res = {}
for t in ps: 
    for key, vals in t.items():
        if key not in res:
            res[key] = vals
        else:
            for innerKey, innerVal in vals.items():
                if innerKey not in res[key]:
                    res[key][innerKey] = 0 
                res[key][innerKey] += innerVal

res是

{'three': {'a': 44}, 'two': {'a': -1000}, 'one': {'a': 1805, 'b': 60}}