>> b = ["sweet", "delicious-6ren">
gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:22:26 24 4
gpt4 key购买 nike

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

关于python - 压缩后如何保持字典的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14627732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com