我对python很新,我有疑问
我有一个dict的词典,看起来像
{"boy" : { "NN" : 3 ,"VB" : 3, "PP" : 2 } }
如果上面的示例中显示了值冲突,我想根据键的降序对内部字典进行排序。答案应该如下:
{"boy" : {"VB" : 3, "NN" : 3, "PP":2} }
我该怎么做?
答案 0 :(得分:2)
使用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))
答案 1 :(得分:0)
您可以像这样对内部词典进行排序:
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)])}