【发布时间】:2015-05-29 14:28:32
【问题描述】:
当键是数字时,我对 python 中的字典属性有疑问。 在我的情况下,当我打印带有数字键的字典时,打印的结果将按键排序,但在另一种情况下(键是字符串)字典是无序的。我想知道字典中的这条规则。
l = {"one" : "1", "two" : "2", "three" : "3"}
print(l)
l = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five"}
print(l)
l = {2: "two", 3: "three", 4: "four", 1: "one", 5: "five"}
print(l)
结果:
{'three': '3', 'two': '2', 'one': '1'}
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
【问题讨论】:
-
Python 字典本质上是未排序的。你不能指望他们的订单,它不会被保留。
-
整数键字典以相同顺序出现的原因可能与 Python 缓存小数字的方式有关。打印此字典
{500000: 'five', 400000: 'four', 30000: 'three', 200000000: 'two', 10: 'one'},您会看到不再保留数字顺序。 -
谢谢,我知道了
标签: python-3.x dictionary numbers key