Home > Blockchain >  Sum of values from multiple dicts
Sum of values from multiple dicts

Time:07-21

I am iterating some code over a directory and I want to sum the values of same keys from dictionaries that I get.

The code is counting how many times a word appears in a column of a .csv file. It does that with every .csv file in the given folder.

I want an output of added values of same keys. Eg. first file had the word "dog" three times and the second had it 4 times. I want to add these two numbers.

The code to count words:

for file in os.scandir(directory):
    if file.path.endswith(ext):
        df = pd.read_csv(file)
        klasifikacija = df.iloc[:, 4]  # Gets all rows for the fourth column (index starts at 0)
        napake = klasifikacija.value_counts()
        dict_napake = dict(napake)

CodePudding user response:

You can make a list of all the dicct_napake you have iterated through and do the following:

import collections
import functools
import operator

dict_napake_1 = {'a': 5, 'b': 1, 'c': 2}
dict_napake_2 = {'a': 2, 'b': 5}
dict_napake_3 = {'a': 10, 'c': 10}  


master_dict = [dict_napake_1,
           dict_napake_2,
           dict_napake_3]

# sum the values with same keys
res = dict(functools.reduce(operator.add,
                            map(collections.Counter, master_dict)))

print("New dict : ", res)
  • Related