简体   繁体   中英

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. 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?

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:

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

Just for clarification, the data structure you're using is a python "dictionary" not an array. 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.

If you want the dictionary in order, you can use a structure called an OrderedDict:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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