1

字典仅在大约 1,2 或 3 个元素时保持正确的顺序

>>> a = ["dorian", "strawberry", "apple"]
>>> b = ["sweet", "delicious", "tasty"]
>>> c = dict(zip(a, b))
>>> c
{'dorian': 'sweet', 'strawberry': 'delicious', 'apple': 'tasty'}

但是当有超过3个元素时,顺序就被打破了

>>> a = ["dorian", "strawberry", "apple", "coconut"]
>>> b = ["sweet", "delicious", "tasty", "yum"]
>>> c = dict(zip(a, b))
>>> c
{'strawberry': 'delicious', 'coconut': 'yum', 'dorian': 'sweet', 'apple': 'tasty'}

谁能解释一下为什么会这样?谢谢

4

3 回答 3

6

Python 字典不维护任何顺序,您应该使用OrderedDict它。

In [7]: from collections import OrderedDict as od

In [8]: a = ["dorian", "strawberry", "apple"]

In [9]: b = ["sweet", "delicious", "tasty"]

In [10]: dic=od(zip(a,b))

In [11]: dic
Out[11]: OrderedDict([('dorian', 'sweet'), ('strawberry', 'delicious'), ('apple', 'tasty')])
于 2013-01-31T14:11:28.413 回答
1

Pythondict是无序的。改为使用collections.OrderedDict

from collections import OrderedDict as odict

# ...
c = odict(zip(a, b))
于 2013-01-31T14:11:55.553 回答
1

字典是地图数据结构。你永远不能线性保证订单。牺牲这一点,您可以在底层实现中获得速度。

于 2013-01-31T14:12:03.977 回答