I have a list like this:
A = [{u'CI': {u'RP': 1}}, {u'CI': {u'RP': 1}}, {u'JI': {u'RP': 1}}]
and I want merge same keys and increment value in dict.
Example:
From these values :
{u'CI': {u'RP': 1}}, {u'CI': {u'RP': 1}}
I will have:
{u'CI': {u'RP': 2}}
final list result is:
A = [{u'CI': {u'RP': 2}}, {u'JI': {u'RP': 1}]
You can use a
defaultdictfromcollectionsto help here. This is adictthat will create default values for missing keys. Firstly you’ll want adefaultdictthat has a default value of0to do your aggregation. Next you’ll need adefaultdictthat has the first kind ofdefaultdictas its default so you can build up to the two levels.If you really want a list of single key dicts rather than a single dict with different keys you can convert the
defaultdictas follows: