Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why dictionary values aren't in the inserted order?

When i declare a list 1,2,3,4 and i do something with it , even just print i get back the same sequence 1,2,3,4.

But when i do anything with dictionaries , they always change number sequence , like it is being sorted in a twisted way i can't understand .

test1 = [4,1,2,3,6,5]
print test1
test2 = {"c":3,"a":1,"b":2,"d":4}
print test2 

[4, 1, 2, 3, 6, 5]
{'a': 1, 'c': 3, 'b': 2, 'd': 4}

How in the world did 'a' become the first element and 'c' , even if it alphabetically sorted the dictionary it should have been 1,2,3,4 or a,b,c,d not 1,3,2,4 . wT?F @!$!@$#@!

So how do i print , get values from dictionary without changing the positions of the elements .?

like image 673
Viktor Avatar asked May 19 '11 15:05

Viktor


People also ask

Why is dictionary not ordered?

A regular dictionary type does not track the insertion order of the (key, value) pairs and thus iterates through the keys based on how they are stored in the hash table which in turn is based on random values so as to reduce collisions.

Why is dictionary not a sequence in Python?

Because the implementation of a dict is a hashmap or hash table, wich doesn't store the elements in order.

Are dictionary values ordered?

Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and do not allow duplicates. As of Python version 3.7, dictionaries are ordered.

Does dictionary store data in sorted order?

Dictionary is an important data structure that stores data by mapping keys with values. 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.


2 Answers

Dictionaries in Python are unordered by definition. Use OrderedDict if you need the order in which values were inserted (it's available in Python 2.7 and 3.x).

like image 143
Eli Bendersky Avatar answered Oct 19 '22 23:10

Eli Bendersky


dictionary sort order is undefined! Do not rely on it for anything. Look for a sorted dictionary if you really want a sorted dictionary, but usually you don't need one.

Examples:

  • python 2.7, it's built in to the collections module
  • Django has a SortedDict shipped with it
  • 2.4-2.7 you can use the ordereddict module, you can pip install or easy_install it
like image 37
Henry Avatar answered Oct 19 '22 23:10

Henry