为什么Python中的字典似乎颠倒了?为什么字典似乎被颠倒?
>>> a = {'one': '1', 'two': '2', 'three': '3', 'four': '4'}
>>> a
{'four': '4', 'three': '3', 'two': '2', 'one': '1'}
我该如何解决这个问题?
为什么Python中的字典似乎颠倒了?为什么字典似乎被颠倒?
>>> a = {'one': '1', 'two': '2', 'three': '3', 'four': '4'}
>>> a
{'four': '4', 'three': '3', 'two': '2', 'one': '1'}
我该如何解决这个问题?
Python中的字典(以及一般的哈希表)是无序的。在Python中,您可以使用键上的sort()
方法对它们进行排序。
好吧,我将使用键/值 – myfreeweb 2010-02-18 19:44:58
你会期待什么是“标准订单”?它非常依赖于应用程序。一个python字典并不能保证密钥排序。
在任何情况下,您都可以按照您想要的方式迭代字典keys()。
词典没有固有的顺序。你必须要么滚动你自己的命令字典执行,使用ordered list
of tuple
s或使用existing ordereddict
implementation。
现在你知道类型的字典是无序的,这里是如何将它们转换为您可以为了
>>> 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')]
>>>
最好是认为字典作为 一组无序的键:值对
而且从Python Standard Library(约dict.items):
CPython实现细节:键 和值以任意 的顺序列出,它是非随机的,变化为跨Python实现的和 取决于字典的 插入和删除的历史记录。
所以,如果你需要处理的一定顺序的字典,排序键或值,例如:
>>> sorted(a.keys())
['four', 'one', 'three', 'two']
>>> sorted(a.values())
['1', '2', '3', '4']
Python3.1有OrderedDict
>>> 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
太棒了。但是我没有对Python 2进行排序。 – myfreeweb 2010-02-19 12:54:32
Orderedicts中的项目按项目添加到词典时排序,而不是按键或项目。所以,如果你不按顺序添加项目 - OrderedDict不会帮助:-) – 2014-09-22 12:30:06
“修复”是什么意思?你会喜欢什么样的顺序? – 2010-02-18 20:31:04