Python: how to disable auto sort when creating a dictionary

I need help for this case:

m={} m[1]=1 m[333]=333 m[2]=2 # Result: {1: 1, 2: 2, 333: 333} 

so even when I did not enter "333" last, I got this "333", indicated at the end of the dictionary when printing it. why does this "dictionary" perform auto sorting? and how to disable it? I can create a re-sort function to fix the order. but this is not what I want, I just want to print and get the output order, just like the order when I enter the data. Is there a good explanation and is there any solution?

+6
source share
2 answers

This is not a sort. dict is not ordered at all, so you canโ€™t influence the order of the keys in any way. There is collections.OrderedDict in versions 2.7 and 3.1+, as well as a stand-alone module for 2.4-2.6.

+20
source

Elements stored in the dictionary do not have a built-in order. The order they print depends entirely on the hash values โ€‹โ€‹for each of the keys and other elements in the dictionary.

+1
source

Source: https://habr.com/ru/post/914453/


All Articles