Dictionaries in Python

This post is been taken from my article which is published by Experts-Exchange.

Dictionaries contain key value pairs. In python we can define dictionaries using dictionary construct.
First of all we need to define a dictionary:
Syntax:
<>  ={<> : <> , <> : <>, …<> : <>  }

From the above syntax the value can be integer may not be enclosed by single/double quotes and separated by commas.
Example:


>>> COURSE ={'ORACLE': 1 ,'LINUX' : 2, 'SHELL' : 3 ,'PERL' : 4 }

>>> type(COURSE)

<type 'dict'>

The dictionaries are also case sensitive. We can access the above dictionary as like below:

>>> COURSE
{'ORACLE': 1, 'PERL': 4, 'SHELL': 3, 'LINUX': 2}
 

This will display the key and values within the dictionary, this are not ordered and if we want the dictionary to be in order then we have to sort it by values as the each key can be unique.
If we want to display the value specifically then we can call the dictionary by each key as like below:

>>> COURSE ['PERL']
4
 

 

Now if we want to add another element let say ‘PYTHON’ as value 4 then use as below:

>>> COURSE ['PYTHON']  = 4
>>> COURSE
{'ORACLE': 1, 'PERL': 4, 'PYTHON': 4, 'SHELL': 3, 'LINUX': 2}
>>> 
 

Now if I want to change the value of the key Linux then we have to use as like below:

>>> COURSE ['PYTHON']  = 9
>>> COURSE
{'ORACLE': 1, 'PERL': 4, 'PYTHON': 9, 'SHELL': 3, 'LINUX': 2}
>>> 
 

If we want to display the keys and values of a dictionary then we have to execute the name of the dictionary with key or values as like below:

>>> COURSE.keys()
['ORACLE', 'PERL', 'PYTHON', 'SHELL', 'LINUX']
>>> COURSE.values()
[1, 4, 9, 3, 2]
 

For deleting the key value pair from the dictionary created then we have to use :

>>> del COURSE['PERL']
>>> COURSE
{'ORACLE': 1, 'PYTHON': 9, 'SHELL': 3, 'LINUX': 2}
>>> 
  

Now we can see that the element PERL is deleted from the dictionary.
Let us see how we can loop the dictionary values:

>>> for key,val in COURSE.iteritems():
                print key,val
 
               
ORACLE 1
PYTHON 9
SHELL 3
LINUX 2
>>> 
 

 

For more information on dictionaries please visit :
https://www.python.org/doc/

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s