/  Technology   /  Are dictionaries ordered in python?

Are dictionaries ordered in python?

 

Dictionary is an unordered collection of data in the form of key:value pairs separated by commas inside curly brackets.

 

Unlike sequences, which are iterables that support accessing of elements using integer indexing, dictionaries are indexed by keys. Dictionaries are generally optimized to retrieve values when the key is known.

>>capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}
>>capitals["USA"]
'Washington DC'

 

Dictionaries map keys to values and based on how they are stored in the hash table(the value never changes during the key’s lifetime with which it is mapped), we can iterate through the keys of a dictionary.

 

In the process to avoid collisions in storing the values in the hashtable, it doesn’t keep track of the insertion order of the (key, value) pairs and this is what makes it unordered.

 

The OrderedDict on the contrary remembers the insertion order of (key, value) pairs in the dictionary and thus preserves the order. It is a standard library class, which is located in the collections module.

 

To use it we must first import it from the collections standard library module.

import collections

 

Let’s see an example

import collections
#Create normal dict
dict = {}
dict['A'] = 1
dict['B'] = 2
dict['C'] = 3
dict['D'] = 4
for item in dict.items():
   print(item)
print()

 

#Create ordered dict

ord_dict = collections.OrderedDict()
ord_dict['A'] = 1
ord_dict['B'] = 2
ord_dict['C'] = 3
ord_dict['D'] = 4
for item in ord_dict.items():
   print(item)

Output

('A', 1)
('C', 3)
('B', 2)
('D', 4)

('A', 1)
('B', 2)
('C', 3)
('D', 4)

 

In this example, we can see that the ordering of the Dict may vary. But for the OrderedDict the order will be fixed.

 

The OrderedDict actually consumes more memory than a regular dictionary in Python because of the usage of Doubly LinkedList to preserve the order.

Leave a comment