python中是否有字典值打印顺序?

2024-04-20 12:21:30 发布

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

当我们在字典中打印值时,是否有用于在Python字典中打印键和值的默认排序?或者他们随机打印键、值对?你知道吗

请看下面的代码。 python中是否有字典值打印顺序?你知道吗

confusion = {}

confusion[1] = 1
confusion[4] = 22
confusion['5'] = 2
confusion['2'] = 2
confusion[1.0] = 4
confusion['1'] = 2

print confusion

结果是{'2': 2, 1: 4, '1': 2, '5': 2, 4: 22}


Tags: 代码字典排序顺序printconfusion
3条回答

引用documentation

CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

不,根据定义字典是无序的。您在这里看到的内容可能会随着版本和平台的不同而变化

如果要保持插入顺序,请使用^{}。默认情况下,python的dict不维护顺序。你知道吗

相关问题 更多 >