Thursday, March 11, 2021

A descriptive article on - What are Ordered Dictionary Objects in Python and how to create them ( code over Jupyter Notebook IDE )

 



Ordered Dictionaries in Python


 

* The elements of a dictionary are not ordered . It means that the elements are not stored in the same order as they were entered into a dictionary

 

* For example , one can consider an employee database in a company which stores the employee details depending upon their seniority that is senior most employee's data may be inserted in the beginning of the database

 

* If the employee's details are stored in a dictionary , then the database will not show the employee details in the same order

 

* When the employee's details are changed , the seniority is disturbed and the data of the employee who joined the company first may not appear in the beginning of the dictionary .

 

* In such a case , the solution is to use ordered dictionaries .

 

* An Ordered Dictionary is a dictionary but it will keep the order of the elements in it . The elements are stored and maintained in the same order as they were entered into the ordered dictionary .

 

* One can create an ordered dictionary using the OrderedDict() method of the collections module . Therefore , we should import the method from the collections module as provided :

 

from collections import OrderedDict

 

Once the ordered dictionary item is created , one can assign an ordered dictionary with the name 'd' as given in the case :

 

d = OrderedDict()

 

One can store the key and values into the ordered dictionary 'd' as in the given manner :

 

d[10] = 'A'

d[11] = 'B'

d[12] = 'C'

d[13] = 'D'

 

Here , 10 is the identifier "Key" and its associated value is "A" . Therefore , the order is not disturbed as 'd' is the ordered dictionary . When we display the key-value pairs from the dictionary 'd' , we can see the same order .

 

=========================================

      Python Program to create a dictionary that

        does not change the order of Elements

=========================================

# create an ordered dictionary from

# collections import OrderedDict

 

d = OrderedDict()

d[10] = 'A'

d[11] = 'B'

d[12] = 'C'

d[13] = 'D'

# display the ordered Dictionary

for i , j in d.items():

    print(i,j)

 

Output

10 - A

11 - B

12 - C

13 - D




 

No comments:

Post a Comment