简体   繁体   English

在Python中对字典的字典进行排序

[英]Sorting a dict of dict in python

I am pretty new to python and I have a doubt 我对python很陌生,我对此表示怀疑

I have a dict of dict which looks like 我有一个像

{"boy" : { "NN" : 3 ,"VB" : 3, "PP" : 2 } }

In case of a conflict of values as shown in the example above , I want to sort the internal dict based on their keys in descending order. 如上例所示,如果发生值冲突,我想根据内部字典的键以降序对它们进行排序。 The answer should look like : 答案应如下所示:

{"boy" : {"VB" : 3, "NN" : 3, "PP":2} }

How can I do that ? 我怎样才能做到这一点 ?

Use an OrderedDict . 使用OrderedDict

from collections import OrderedDict
outer_dict = {"boy" : { "NN" : 3 ,"VB" : 3, "AA" : 2 } }
for key in outer_dict:
    inner_dict = outer_dict[key]
    outer_dict[key] = OrderedDict(sorted(inner_dict.items(), reverse=True))

You could sort the inner dictionaries like this: 您可以像这样对内部字典进行排序:

from collections import OrderedDict

dict_of_dict = {"boy" : { "NN" : 3 ,"VB" : 3, "AA" : 2 } }

# sort inner dictionaries by descending key values
dict_of_dict = {key: OrderedDict(sorted(inner_dict.items(), reverse=True))
                    for key, inner_dict in dict_of_dict.items()}

print(dict_of_dict) # -> {'boy': OrderedDict([('VB', 3), ('NN', 3), ('AA', 2)])}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM