Search code examples
pythonlistdictionarysumaccumulator

How to make an element of a dict accumulate other elements in python


I have the following structure of python dictionary lists (let's call it dict1):

dict1 = {"word1": {'111.txt': 1, '112.txt': 3, '113.txt': 2},
         "word2": {'111.txt': 2, '112.txt': 2, '113.txt': 1},
         "word3": {'111.txt': 1, '113.txt': 1},
         "word4": {'111.txt': 3, '113.txt': 2},
         "word5": {'111.txt': 5, '113.txt': 1}}

and I would like to create a new dictionary (dict2), where I have the keys of dict1 and the sum of the elements of that key as its elements. Thus:

{'111.txt': 12, '112.txt': 5, '113.txt': 7}

I tried to do the following code below, however, it is only storing the last element of dict1 in dict2, that is, it is not accumulating the values ​​of dict1

for i,j in dict1.items():
     for k,w in j.items():
            dict2[k] =+ j[k]

The output is as follows, it leaves only the last element of dict1, it is not accumulating the sum.

{'111.txt': 5, '112.txt': 2, '113.txt': 1}

Does anyone know what may be wrong in the code? Or do you have a better idea?


Solution

  • I believe the error is in the way you initialise dict2 but can't tell much since you haven't posted that part. This should work though:

    dict1 = {"word1": {'111.txt': 1, '112.txt': 3, '113.txt': 2},
             "word2": {'111.txt': 2, '112.txt': 2, '113.txt': 1},
             "word3": {'111.txt': 1, '113.txt': 1},
             "word4": {'111.txt': 3, '113.txt': 2},
             "word5": {'111.txt': 5, '113.txt': 1}}
    
    dict2 = dict()
    
    for i, j in dict1.items():
        for k, w in j.items():
            dict2[k] = dict2.get(k, 0) + j[k]
    
    print(dict2)
    

    output:

    {'112.txt': 5, '113.txt': 7, '111.txt': 12}