2010-02-18 79 views
1

为什么Python中的字典似乎颠倒了?为什么字典似乎被颠倒?

>>> a = {'one': '1', 'two': '2', 'three': '3', 'four': '4'} 
>>> a 
{'four': '4', 'three': '3', 'two': '2', 'one': '1'} 

我该如何解决这个问题?

+1

“修复”是什么意思?你会喜欢什么样的顺序? – 2010-02-18 20:31:04

回答

16

Python中的字典(以及一般的哈希表)是无序的。在Python中,您可以使用键上的sort()方法对它们进行排序。

+0

好吧,我将使用键/值 – myfreeweb 2010-02-18 19:44:58

0

你会期待什么是“标准订单”?它非常依赖于应用程序。一个python字典并不能保证密钥排序。

在任何情况下,您都可以按照您想要的方式迭代字典keys()。

5

词典没有固有的顺序。你必须要么滚动你自己的命令字典执行,使用ordered list of tuples或使用existing ordereddict implementation

+0

404.断开链接! – myfreeweb 2010-02-18 19:44:35

+0

@myfreeweb:有两个链接,我可以访问他们两个http://www.voidspace.org.uk/python/odict.html http://code.activestate.com/recipes/107747/ – voyager 2010-02-18 20:11:53

2

现在你知道类型的字典是无序的,这里是如何将它们转换为您可以为了

>>> a = {'one': '1', 'two': '2', 'three': '3', 'four': '4'} 
>>> a 
{'four': '4', 'three': '3', 'two': '2', 'one': '1'} 

通过关键

>>> sorted(a.items()) 
[('four', '4'), ('one', '1'), ('three', '3'), ('two', '2')] 

分类排序由值列表

>>> from operator import itemgetter 
>>> sorted(a.items(),key=itemgetter(1)) 
[('one', '1'), ('two', '2'), ('three', '3'), ('four', '4')] 
>>> 
0

Python Tutorial

最好是认为字典作为 一组无序的键:值对

而且从Python Standard Library(约dict.items):

CPython实现细节:键 和值以任意 的顺序列出,它是非随机的,变化为跨Python实现的和 取决于字典的 插入和删除的历史记录。

所以,如果你需要处理的一定顺序的字典,排序键或值,例如:

>>> sorted(a.keys()) 
['four', 'one', 'three', 'two'] 
>>> sorted(a.values()) 
['1', '2', '3', '4'] 
5

Python3.1OrderedDict

>>> from collections import OrderedDict 
>>> o=OrderedDict([('one', '1'), ('two', '2'), ('three', '3'), ('four', '4')]) 
>>> o 
OrderedDict([('one', '1'), ('two', '2'), ('three', '3'), ('four', '4')]) 
>>> for k,v in o.items(): 
... print (k,v) 
... 
one 1 
two 2 
three 3 
four 4 
+0

太棒了。但是我没有对Python 2进行排序。 – myfreeweb 2010-02-19 12:54:32

+0

Orderedicts中的项目按项目添加到词典时排序,而不是按键或项目。所以,如果你不按顺序添加项目 - OrderedDict不会帮助:-) – 2014-09-22 12:30:06