[英]Why dictionaries appear to be reversed?
为什么python中的字典看起来相反?
>>> a = {'one': '1', 'two': '2', 'three': '3', 'four': '4'}
>>> a
{'four': '4', 'three': '3', 'two': '2', 'one': '1'}
我怎样才能解决这个问题?
python中的字典(通常是哈希表)是无序的。 在python中,您可以在键上使用sort()
方法对它们进行排序。
字典没有内在顺序。 您将必须滚动自己的有序dict实现,使用tuple
的有序list
或使用现有的有序 dict
实现 。
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
现在您知道字典是无序的,这是如何将它们转换为可以排序的列表
>>> 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字典仍然不能保证键顺序。
无论如何,您都可以按照自己的方式遍历字典keys()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.