繁体   English   中英

为什么字典看起来是相反的?

[英]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()。

Python教程

最好将字典视为无序的键集:值对

并且来自Python标准库 (关于dict.items):

CPython实现细节:键和值以任意顺序列出,该顺序是非随机的,在Python实现中会有所不同,并且取决于字典的插入和删除历史。

因此,如果您需要按特定顺序处理字典,请对键或值进行排序,例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM