发现一个秘密:既python3.6之后字典竟然变成了有序集合,我再次验证了一下!

file

高版本我一直使用的是3.8的版本,我先用python3.8的版本来测试查看是不是会产生有序的字......

【阅读全文】

test_dict = {'o': 1,'p': 2,'q': 3,'r': 4,'s': 5,'t': 6}

使用ksys()函数验证字典的键是否有序

print(test_dict.keys())

# dict_keys(['o', 'p', 'q', 'r', 's', 't'])
# Process finished with exit code 0

遍历字典再次验证

for key,value in test_dict.items():
    print(key,value)

# dict_keys(['o', 'p', 'q', 'r', 's', 't'])
# o 1
# p 2
# q 3
# r 4
# s 5
# t 6

发现python3.8版本的字典集合真的变成有序字典了。最后,找个3.6以下的版本再来验证一番,使用同样的数据来进行验证

# Python 2.7.18 (v2.7.18:8d21aa21f2, Apr 20 2020, 13:25:05) [MSC v.1500 64 bit (AMD64)] on win32
# Type "help", "copyright", "credits" or "license" for more information.
# >>> test_dict = {'o': 1,'p': 2,'q': 3,'r': 4,'s': 5,'t': 6}
# >>> print(test_dict.keys())
# ['o', 'q', 'p', 's', 'r', 't']
# >>>

首先keys()函数遍历的键就是无序的

# >>> for key,value in test_dict.items():
# ...     print(key,value)
# ...
# ('o', 1)
# ('q', 3)
# ('p', 2)
# ('s', 5)
# ('r', 4)
# ('t', 6)

最后,遍历的键值都是无序的。今天就到这里了,小编才加完班该回家了!

file

【往期精彩】

这么多的内置函数能记住吗?对python的68个内置函数分类总结!

必须要会的文件操作对象File,python文件读写操作利器!

你不知道的CS模式的进程管理工具,状态监测、项目启停一目了然!

如何将一个python应用以docker镜像的方式来运行?

python超赞插件you-get,执行一行命令即可下载、命令行下载工具推荐!

posted @ 2021-10-29 23:43  Python集中营  阅读(208)  评论(0编辑  收藏  举报