So I am trying to sum the values of nested keys and sort the key values by this value. I have a nested dict like the following:
dict_items([('“The', {'T': 1}), ('reason', {'T': 1}), ('we', {'T': 1, 'O': 1}), ('have', {'T': 1, 'O': 1}),...
I want to sum the values associated with the keys 'O'
and 'T'
and then sort the words The
, reason
... by the values produced by summing each of their 'O'
and 'T'
values so that I get a dict back with the word and its value.
So far I have the following which returns the counts of the words but not the words attached:
sorted([sum(i[1].values()) for i in dct.items()], reverse=True)
I have tried the following, but I get a key error with 'O'
my_word_dct = sorted(dct.items(), key = lambda x: x[1]['O'] + x[1]['T'], reverse = True)
Any ideas where I am going wrong?
EDIT: The expected output would be something like:
{'we':2, 'have':2, 'The':1, 'reason':1...}
Thanks in advance!!
You want the.get() function in case your dictionary doesn't have the key in question.
x[1].get('O',0) + x[1].get('T',0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.