Aggregate items in a dict

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 to combine the same keys and increment value in a dict.

Example:

From these values:

{u'CI': {u'RP': 1}}, {u'CI': {u'RP': 1}}

I will have:

{u'CI': {u'RP': 2}}

The end result of the list:

A = [{u'CI': {u'RP': 2}}, {u'JI': {u'RP': 1}]
+5
source share
4 answers

You can use from to help here. This will create default values ​​for missing keys. First, you will need one that has a default value for your aggregation. Then you need , for which the first type is used by default, so you can create up to two levels. defaultdictcollectionsdictdefaultdict0defaultdictdefaultdict

>>> A = [{u'CI': {u'RP': 1}}, {u'CI': {u'RP': 1}},  {u'JI': {u'RP': 1}}]
>>> B = defaultdict(lambda: defaultdict(int))
>>> for d in A:
...     for (key,d2) in d.iteritems():
...         for (key2, value) in d2.iteritems():
...             B[key][key2] += value
... 
>>> B.items()
[(u'CI', defaultdict(<type 'int'>, {u'RP': 2})), (u'JI', defaultdict(<type 'int'>, {u'RP': 1}))]

dict, dict , defaultdict :

>>> [{key: dict(value)} for key,value in B.iteritems()]
[{u'CI': {u'RP': 2}}, {u'JI': {u'RP': 1}}]
+7

setdefault dict:

A = [{u'CI': {u'RP': 1}}, {u'CI': {u'RP': 1}},  {u'JI': {u'RP': 1}}]
B = {}
for i in A:
     k = i.keys()[0]             # k is 'CI' or 'JI' in this case
     B.setdefault(k, {u'RP': 0}) # set the default 'RP' to 0
     B[k]['RP'] += i[k][u'RP']   # add the RP. Because we already 
                                 # set the default to 0 this will not blow up
print B
# {u'CI': {u'RP': 2}, u'JI': {u'RP': 1}}
+1

, , .

Python 2, .

A = [{u'CI': {u'RP': 1}}, {u'CI': {u'RP': 1}}, {u'JI': {u'RP': 1}}]
B = {}
for item in A:
    key = item.keys()[0]
    subDict = item.values()[0]
    existingSubDict = B[key] if key in B else {}
    for subKey, value in subDict.iteritems():
        if not subKey in existingSubDict:
            existingSubDict[subKey] = 0
        existingSubDict[subKey] += value
    B[key] = existingSubDict
print B

{u'CI ': {u'RP': 2}, u'JI ': {u'RP': 1}}

0

, , : B.initialize() B.update() , :

B = {}
for i in A: 
    if i not in B: 
        B.initialize(i)
    B.update(i,A[i])

:

B = {}
for i in A: 
    if i not in B: 
        B[i] = 0
    B[i] += A[i] 

, , , , , , , {u'CI ': {u'RB': 1, u ' RP ': 1}}.

0
source

All Articles