小编lor*_*ian的帖子

python中的字典顺序

无论我在哪里搜索,他们都说python词典没有任何顺序.当我运行代码1时,每次显示不同的输出(随机顺序).但是当我运行代码2时,它总是显示相同的排序输出.为什么字典在第二个片段中排序?

   #code 1

    d = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
    for a, b in d.items():
        print(a, b)
   #code 2 

    d = {1: 10, 2: 20, 3: 30, 4: 40}
    for a, b in d.items():
        print(a, b)
Run Code Online (Sandbox Code Playgroud)

输出

代码1:

four 4
two 2
three 3
one 1
Run Code Online (Sandbox Code Playgroud)

代码1:

three 3
one 1
two 2
four 4
Run Code Online (Sandbox Code Playgroud)

代码2(总是):

1 10
2 20
3 30
4 40
Run Code Online (Sandbox Code Playgroud)

python dictionary

5
推荐指数
1
解决办法
216
查看次数

标签 统计

dictionary ×1

python ×1