简体   繁体   English

Python如何处理混合类型的字典键排序,为什么?

[英]How does Python handle ordering dictionary keys with mixed types and why?

I'm trying to create a dictionary where the indices are a mix of strings ('20' & '0') and integers (10 & 11) but every time the dictionary is printed out the output seems to change randomly. 我正在尝试创建一个字典,其中的索引是字符串(“ 20”和“ 0”)和整数(10和11)的混合,但是每次打印出字典时,输出似乎都是随机变化的。 I've read that dictionaries in python are supposed to maintain the order of the elements inserted to the dictionary, so why does this shuffling of the elements occur? 我已经读过python中的字典应该保持插入字典中的元素的顺序,那么为什么会发生元素的这种混排呢?

arr = {};
arr['20'] = "hello"
arr['0'] = "hey"
arr[10] = "hi"
arr[11] = "yo"

print(arr)

I would expect the output to be: 我希望输出为:

{'20: 'hello', '0': 'hey', 10: 'hi', 11: 'yo'}

but the output ends up reordering each element in the array and converting 10 & 11 into strings: 但是输出最终重新排列数组中的每个元素并将10和11转换为字符串:

{'20': 'hello', 10: 'hi', 11: 'yo', '0': 'hey'}

Just for clarification, the data structure you're using is a python "dictionary" not an array. 为了澄清起见,您使用的数据结构是python“字典”而不是数组。 It maps keys to values. 它将键映射到值。 Python dictionaries do not have an internal ordering, so it will simply print in the order you've entered it in. Python字典没有内部顺序,因此它只会按照您输入的顺序打印。

If you want the dictionary in order, you can use a structure called an OrderedDict: 如果要按顺序排列字典,则可以使用称为OrderedDict的结构:

from collections import OrderedDict
exampleDict = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM