如何在压缩后保持字典的整洁

2024-04-28 12:38:53 发布

您现在位置:Python中文网/ 问答频道 /正文

当只有大约1、2或3个元素时,字典会正确地保持顺序

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

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

^{pr2}$

有人能解释一下为什么会这样吗?谢谢


Tags: 元素apple字典顺序zipdicttastysweet
3条回答

Python字典不维护任何顺序,您应该使用^{}。在

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')])

Python^{}s are unordered。请改用^{}。在

from collections import OrderedDict as odict

# ...
c = odict(zip(a, b))

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

相关问题 更多 >