Skip to main content
 首页 » 编程设计

python之压缩后如何保持字典的顺序

2025年05月04日14findumars

当只有大约 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'} 

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

请您参考如下方法:

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