使用有序键列表在Python中排序字典 [英] Sorting a dictionary in Python using a list of ordered keys

查看:162
本文介绍了使用有序键列表在Python中排序字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我认为题目很好地解释了这个问题。
我需要帮助一个功能,可以通过有序键列表对字典进行排序。我想要一个最佳解决方案。

So, I think the title explains the problem pretty well. I need help with a function that would sort the dictionary by a list of ordered keys. I would want an optimal solution.

示例:

>>> keyorder = ['a', 'c', 'b']
>>> mydict = {'c': 2, 'a': 1, 'b': 3}
>>> sorted_list = sortdictbykeys(mydict, keyorder)
>>> sorted_list
[1, 2, 3]


推荐答案

我可能会丢失一些东西,但是不能执行以下工作:

I might be missing something but wouldn't the following work:

[mydict[stackoverflow] for stackoverflow in keyorder]

应该产生:

[1,2,3]

这篇关于使用有序键列表在Python中排序字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆