How can I take a list of dicts like this:
ps = [{'one': {'a': 30,
"b": 30},
'two': {'a': -1000}},
{'three': {'a': 44}, 'one': {'a': -225}},
{'one': {'a': 2000,
"b": 30}}]
and produce a dict of dicts like this:
{"one": {"a": 1805, "b": 60}, "two": {"a": -1000}, "three": {"a": 44}}
I'm pretty sure I can use a collections.Counter() to do this, but what I have so far doesn't work. it just returns whatever the last value of a
or b
was for each element:
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})
I'm new to python so excuse what I'm sure is ugly code.