user3058703 user3058703 -4 years ago 214
Python Question

Add new field for Python dictionary

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?

Answer Source

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()}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download