Python:排序字典词典

ytr*_*ewq 15 python sorting dictionary

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

wd[wc][dist][True]={'course': {'#': 1, 'Fisher': 4.0},
 'i': {'#': 1, 'Fisher': -0.2222222222222222},
 'of': {'#': 1, 'Fisher': 2.0},
 'will': {'#': 1, 'Fisher': 3.5}}
Run Code Online (Sandbox Code Playgroud)

我想通过相应的'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}}
Run Code Online (Sandbox Code Playgroud)

我已尝试使用items()和sorted()但无法解决...请帮助我:(

Ash*_*ary 29

您不能对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})
]
Run Code Online (Sandbox Code Playgroud)

或者collections.OrderedDict在获取排序(键,值)对后创建(在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})
])
Run Code Online (Sandbox Code Playgroud)

对于你的字典,试试这个:

>>> 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))
Run Code Online (Sandbox Code Playgroud)


Joh*_*ooy 5

如果您只需要按顺序排列密钥,您可以获得这样的列表

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'])
Run Code Online (Sandbox Code Playgroud)

如果“Fisher”可能丢失,您可以使用它来将这些条目移至最后

sorted(dic, key=lambda x:dic[x].get('Fisher', float('inf')))
Run Code Online (Sandbox Code Playgroud)

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