python以什么顺序显示字典键? [英] In what order does python display dictionary keys?

查看:46
本文介绍了python以什么顺序显示字典键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<预><代码>>>>D = {'a':1,'b':2,'c':3}>>>D{'a':1,'c':3,'b':2}

我刚刚在 Python shell 中做了这个,我只是想知道为什么键 'c' 会在键 'b' 之后???

解决方案

顺序与它们在内部的工作方式以及它们在哈希表中的最终顺序有关.这反过来又取决于键的哈希值、它们插入的顺序以及您使用的 Python 实现.

顺序是任意的(但不是随机的),而且知道顺序是什么也无济于事.

要获得排序的键列表,只需使用 sorted(D),在您的情况下将返回 ['a', 'b', 'c'].

>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> D
{'a': 1, 'c': 3, 'b': 2}

I just did this in the Python shell and I'm just wondering why the key 'c' would be after the key 'b'???

解决方案

The order has to do with how they work internally and what order they end up in the hashtable. That in turn depends on the keys hash-value, the order they were inserted, and which Python implementation you are using.

The order is arbitrary (but not random) and it will never be useful to know which order it will be.

To get a sorted list of keys, just use sorted(D), which in your case will return ['a', 'b', 'c'].

这篇关于python以什么顺序显示字典键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆