i have a list of dicts in python like this:
[
{
"25-34": {
"Clicks": 10
},
"45-54": {
"Clicks": 2
},
},
{
"25-34": {
"Clicks": 20
},
"45-54": {
"Clicks": 10
},
}
]
how can i get the sum of keys in each dict of list such that i have:
{
"25-34": {
"Clicks": 30
},
"45-54": {
"Clicks": 12
},
}
I tried using Counter() but it works easily when the dicts inside list are flat but with the nested dicts like above it gives this error:
/usr/lib/python2.7/collections.pyc in update(self, iterable, **kwds)
524 self_get = self.get
525 for elem, count in iterable.iteritems():
--> 526 self[elem] = self_get(elem, 0) + count
527 else:
528 super(Counter, self).update(iterable) # fast path when counter is empty
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
How can i achieve the summation as i described above.
NOTE: i have added clicks just for sample. nested dicts can have any no of keys,
another example to make it more clear:
[
{
"25-34": {
"Clicks": 10,
"Visits": 1
},
"45-54": {
"Clicks": 2,
"Visits": 2
},
},
{
"25-34": {
"Clicks": 20,
"Visits": 3
},
"45-54": {
"Clicks": 10,
"Visits": 4
},
}
]
output:
{
"25-34": {
"Clicks": 30,
"Visits": 4
},
"45-54": {
"Clicks": 12,
"Visits": 6
},
}