排序字典python 3 [英] sorting dictionary python 3

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

问题描述

我正在使用python 3.2.2。
折断我的头超过3个小时,以按键对字典进行排序。
我设法使它成为具有2个自变量成员的排序列表,但最终却不能使其成为排序字典。

I'm working on python 3.2.2. Breaking my head more than 3 hours to sort a dictionary by it's keys. I managed to make it a sorted list with 2 argument members, but can not make it a sorted dictionary in the end.

这就是我要做的

myDic={10: 'b', 3:'a', 5:'c'}
sorted_list=sorted(myDic.items(), key=lambda x: x[0])

但是无论如何我都不能从这个排序列表中选出一个字典。我怎么做?谢谢!

But no matter what I can not make a dictionary out of this sorted list. How do I do that? Thanks!

推荐答案

dict 不会保持其元素顺序。您需要的是OrderedDict: http://docs.python.org/library/ collections.html#collections.OrderedDict

dict does not keep its elements' order. What you need is an OrderedDict: http://docs.python.org/library/collections.html#collections.OrderedDict

编辑

用法例如:

>>> from collections import OrderedDict
>>> a = {'foo': 1, 'bar': 2}
>>> a
{'foo': 1, 'bar': 2}
>>> b = OrderedDict(sorted(a.items()))
>>> b
OrderedDict([('bar', 2), ('foo', 1)])
>>> b['foo']
1
>>> b['bar']
2

这篇关于排序字典python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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