如何在压缩后保持字典顺序
字典在只有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'}
有人能解释一下为什么会这样吗?谢谢
3 个回答
1
字典是一种映射数据结构。它的特点是不能保证元素的顺序。如果你愿意放弃这个顺序的保证,就能在底层实现上获得更快的速度。
1
Python中的dict
字典是没有顺序的,也就是说你不能保证里面的元素是按照你添加的顺序排列的。如果你需要保持元素的顺序,可以使用collections.OrderedDict
。
from collections import OrderedDict as odict
# ...
c = odict(zip(a, b))
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')])