Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python : how to disable auto sort when creating 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 didn't enter '333' the last, i got this '333' listed in the end of the dictionary when print it out. why is this 'dictionary' doing auto sort? and how disable it? i can creata a function to re-sort to fix the order. but that's not what i want, i just simply want to print and get output order just like the order when i input the data. Is there any good explanation and is there any solution ?

like image 358
andio Avatar asked Apr 29 '12 09:04

andio


People also ask

Are dictionaries automatically sorted Python?

Items stored in a dictionary do not have any inherent order. The order they are printed out is entirely down to the hash values for each of the keys and the other items in the dictionary.

How do I manually sort a dictionary in Python?

To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.

Is Python dictionary always sorted?

The default dictionaries in Python are unordered data structures. Like lists, we can use the sorted() function to sort the dictionary by keys. However, it will only return a list of sorted keys, which is usually not what we desire.

Does Python dictionary preserve order?

Since dictionaries in Python 3.5 don't remember the order of their items, you don't know the order in the resulting ordered dictionary until the object is created. From this point on, the order is maintained. Since Python 3.6, functions retain the order of keyword arguments passed in a call.


1 Answers

It is not sorting. dict is not ordered at all, so you cannot influence the key order in any way. There is collections.OrderedDict in 2.7 and 3.1+, there is also standalone module for 2.4-2.6.

like image 125
wRAR Avatar answered Nov 15 '22 14:11

wRAR