[英]sort nested dict with sum of nested key values
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.我想对与键
'O'
和'T'
关联的值求和,然后将单词The
, reason
... 通过对它们的每个'O'
和'T'
值求和所产生的值进行排序,以便我得到一个用单词及其值返回。
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'我尝试了以下方法,但出现“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:编辑:预期的 output 将类似于:
{'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.你想要 .get() function 以防你的字典没有问题的关键。
x[1].get('O',0) + x[1].get('T',0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.