为什么我的python词典总是被订购?

2024-03-29 10:51:11 发布

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

我知道Python的字典是无序的。但我不明白为什么我的dict在输出时总是按顺序排列。就像下面的代码一样,无论我如何更改键或值,它总是按顺序打印。谢谢您!你知道吗

num1 = 30
num2 = 192
c1 = 'good'
c2 = 'hello'
a = {'a':8, 'k':c2, 'c':3, 'b':5}
a['g'] = 56
a['jj'] = num2
a['89'] = 'asdfg'
a['u'] =42
a['d'] = c1
a['11'] = 40
a['0'] = num1
print(a)
for key in a:
    print(key, a[key])

output


Tags: key代码hello字典顺序dict无序good
1条回答
网友
1楼 · 发布于 2024-03-29 10:51:11

dict保留python3.6中的插入顺序(由于内部实现),您可以依赖python3.7中的顺序

Python 3.7 release notes

The insertion-order preservation nature of dict objects is now an official part of the Python language spec.

相关问题 更多 >