Add new field for Python dictionary

Issue

I have a dict which I have used Counter to get term frequencies for each key e.g. 'A' and 'B'.

dict = {'A': Counter({'food': 30, 'menu': 19, 'good': 15}), 'B': Counter({'one': 5, 'chicken': 10})}

I would like to be able to add a new field so that each term has another value.

I have tried:

for key, values in dict.items():
    for it1, it2 in values:
         dict[key][it1][it2] = 0

but I receive:

ValueError: too many values to unpack (expected 2)

Do I need to remove the Counter object? How do I create a new value and how do I access this value?

Solution

You’re better off creating an entirely new dictionary, to have that extra nested dict:

dct = {key: {k: {v: 0} for k, v in values.items()} for key, values in dct.items()}

Answered By – Moses Koledoye

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published