Python- 排序字典中的字典

2024-05-29 01:50:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个听写(这也是一个更大的听写的关键)看起来像

wd[wc][dist][True]={'course': {'#': 1, 'Fisher': 4.0},
 'i': {'#': 1, 'Fisher': -0.2222222222222222},
 'of': {'#': 1, 'Fisher': 2.0},
 'will': {'#': 1, 'Fisher': 3.5}}

我想按关键字对应的“Fisher”值对关键字(在最高级别)进行排序。。。 所以输出看起来像

wd[wc][dist][True]={'course': {'Fisher': 4.0, '#': 1}, 'will': {'Fisher': 3.5, '#': 1}, 'of': {'Fisher': 2.0, '#': 1}, 'i': {'Fisher': -0.2222222222222222, '#': 1}}

我试过使用items()和sorted()但无法解决。。。 请帮帮我:


Tags: oftrue排序distitems关键字will关键
2条回答

不能对dict进行排序,但可以获得键、值或(键、值)对的排序列表。

>>> dic = {'i': {'Fisher': -0.2222222222222222, '#': 1}, 'of': {'Fisher': 2.0, '#': 1}, 'will': {'Fisher': 3.5, '#': 1}, 'course': {'Fisher': 4.0, '#': 1}}

>>> sorted(dic.items(), key=lambda x: x[1]['Fisher'], reverse=True)
[('course', {'Fisher': 4.0, '#': 1}),
 ('will', {'Fisher': 3.5, '#': 1}),
 ('of', {'Fisher': 2.0, '#': 1}),
 ('i', {'Fisher': -0.2222222222222222, '#': 1})
]

或者在获得排序(键、值)对之后创建一个^{}(在Python 2.7中引入):

>>> from collections import OrderedDict
>>> od = OrderedDict(sorted(dic.items(), key=lambda x: x[1]['Fisher'], reverse=True))
>>> od
OrderedDict([
('course', {'Fisher': 4.0, '#': 1}),
('will', {'Fisher': 3.5, '#': 1}),
('of', {'Fisher': 2.0, '#': 1}),
('i', {'Fisher': -0.2222222222222222, '#': 1})
])

对于您的字典,请尝试以下操作:

>>> from collections import OrderedDict
>>> dic = wd[wc][dist][True]
>>> wd[wc][dist][True]= OrderedDict(sorted(dic.items(), key=lambda x: x[1]['Fisher'], reverse=True))

如果你只需要把钥匙整理好,你可以得到这样的清单

dic = {'i': {'Fisher': -0.2222222222222222, '#': 1}, 'of': {'Fisher': 2.0, '#': 1}, 'will': {'Fisher': 3.5, '#': 1}, 'course': {'Fisher': 4.0, '#': 1}}
sorted(dic, key=lambda k: dic[k]['Fisher'])

如果“Fisher”可能丢失,您可以使用此选项将这些条目移到最后

sorted(dic, key=lambda x:dic[x].get('Fisher', float('inf')))

或者'-inf'将它们放在开头

相关问题 更多 >

    热门问题