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

23

我有一个字典(也是较大字典的键)的字典,看起来像这样:

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

我希望能按照它们对应的“费舍尔”值来对关键词(在最高层级)进行排序...以便输出看起来像这样

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(),但无法解决问题...请帮我一下 :(


4
很遗憾,你无法对字典进行排序,因为它是无序的。阅读这篇很好的文章,了解如何进行操作:https://dev59.com/EHRB5IYBdhLWcg3weHLx - Henrik Andersson
2021年:对于Python >=3.7,该语言规定字典是有序的,并且CPython实现了这一点。 - DisappointedByUnaccountableMod
请参见以下链接:https://dev59.com/EHRB5IYBdhLWcg3weHLx - DisappointedByUnaccountableMod
2个回答

40

你无法对字典进行排序,但可以获取按键、值或(键,值)对排序后的列表。

>>> 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})
]

或者在获取排序后的(键,值)对之后创建一个 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})
])

尝试使用这个字典:

>>> 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))

1
请注意,OrderedDict 仅适用于 Python 版本 2.7 及以上。 - Burhan Khalid
使用items()会导致KeyError...可能是什么原因? - ytrewq
@CosmicRabbitMediaInc 你的其中一个字典可能没有Fisher键,是这样吗?尝试运行all('Fisher' in d[k] for k in d)并发布输出。 - jamylak
@CosmicRabbitMediaInc 这个答案很好,你的数据结构不是字典。 - jamylak
1
@CosmicRabbitMediaInc 然后尝试使用larger_dict[key].items(),或将问题主体中的更大的dict发布出来。 - Ashwini Chaudhary
显示剩余4条评论

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'])

如果“Fisher”可能缺失,您可以使用这个方法将这些条目移到最后。
sorted(dic, key=lambda x:dic[x].get('Fisher', float('inf')))

或者'-inf'表示将它们放置在开头。


如果条目中没有“Fisher”,您将如何完全删除它们? - Professor Dragon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接