Exploring New Techs!

Python – Dictionaries

                                 

Hello Technotizers, this article is dedicated to the last Python specific data type that is Dictionaries. Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered, changeable and does not allow duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

Dictionaries are written with curly brackets, and have keys and values.

my_address = {                

    "Street" : 8,             

    "Town" : "Kharghar",      

    "City" : "Mumbai"         

}                             

print(my_address)             

The output is obtained as:

{'Street': 8, 'Town': 'Kharghar', 'City': 'Mumbai'}

 

Some points to be remembered:

·         Dictionary items are ordered, changeable, and does not allow duplicates.

·         Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

·         A dictionary item can be of any data type like int, string or Boolean. A dictionary can also contain items of mixed data types.

 

Examples:

The below given dictionary has values of mixed data types and it is valid in Python.

my_address = {            
    "Street" : 8,         
    "Town" : "Kharghar",  
    "City" : "Mumbai",    
    "On highway" : True   
}                         
print(my_address)         

 

·         Accessing dictionary elements:

You can access the items of a dictionary by referring to its key name, inside square braces after the dictionary name.

my_address = {            
    "Street" : 8,         
    "Town" : "Kharghar",  
    "City" : "Mumbai"     
}                         
x = my_address["Town"]    
print(x)                  

The output is obtained as:

Kharghar   

We can also use the get() method to access the dictionary. It is similar like the previous example.

my_address = {            
    "Street" : 8,         
    "Town" : "Kharghar",  
    "City" : "Mumbai"     
}                         
x = my_address.get("Town")

The output is obtained as:

Kharghar  

Another method to access the dictionary is keys() method.

my_address = {          
    "Street" : 8,       
    "Town" : "Kharghar",
    "City" : "Mumbai"   
}                       
print(my_address.keys())

The output is obtained as:

dict_keys(['Street', 'Town', 'City'])

This method returns a list of all the keys from the dictionary.

The values() method will return a list of all the values in the dictionary.

my_address = {            
    "Street" : 8,         
    "Town" : "Kharghar",  
    "City" : "Mumbai"     
}                         
print(my_address.values())

The output is obtained as:

dict_values([8, 'Kharghar', 'Mumbai'])

The items() method will return all the items in a dictionary in the form of a list containing tuples of key value pairs.

my_address = {            
    "Street" : 8,         
    "Town" : "Kharghar",  
    "City" : "Mumbai"     
}                         
print(my_address.items()) 

The output is obtained as:

dict_items([('Street', 8), ('Town', 'Kharghar'), ('City', 'Mumbai')])

 

·         Changing dictionary elements:

Value of a specific dictionary item can be changed by referring to its key.

my_address = {               
    "Street" : 8,            
    "Town" : "Kharghar",     
    "City" : "Mumbai"        
}                            
my_address["Town"] = "Panvel"
print(my_address)            

The output is obtained as:

{'Street': 8, 'Town': 'Panvel', 'City': 'Mumbai' 

The update() method will update the existing dictionary with the items from the given argument. The argument should be a dictionary, or an iterable object with key:value pairs.

my_address = {                       
    "Street" : 8,                    
    "Town" : "Kharghar",             
    "City" : "Mumbai"                
                                   
my_address.update({"Town":"Panvel"}) 
print(my_address)                    

The output is obtained as:

{'Street': 8, 'Town': 'Panvel', 'City': 'Mumbai'}

 

·         Adding new dictionary items:

A new dictionary item is added by using a new index key and assigning a new value to it.

my_address = {                     
    "Street" : 8,                  
    "Town" : "Kharghar",           
    "City" : "Mumbai"              
}                                  
my_address["State"] = "Maharashtra"
print(my_address)                  

The output is obtained as:

{'Street': 8, 'Town': 'Kharghar', 'City': 'Mumbai', 'State': 'Maharashtra'}

The update() method will update the existing dictionary with the items from the given argument. If the item doesn’t exist, then it will be added. The argument should be a dictionary, or an iterable object with key:value pairs.

my_address = {                            
    "Street" : 8,                         
    "Town" : "Kharghar",                  
    "City" : "Mumbai"                     
}                                         
my_address.update({"State":"Maharashtra"})
print(my_address)                         

The output is obtained as:

{'Street': 8, 'Town': 'Kharghar', 'City': 'Mumbai', 'State': 'Maharashtra'}


·         Removing dictionary items:

The pop() method removes the item with the specified key name.

my_address = {           
    "Street" : 8       
    "Town" : "Kharghar"
    "City" : "Mumbai"    
}                        
my_address.pop("Town")   
print(my_address)        

The output is obtained as:

{'Street': 8, 'City': 'Mumbai'}

The popitem() method removes the last inserted item.

In versions before 3.7, a random item is removed.

my_address = {           
    "Street" : 8       
    "Town" : "Kharghar"
    "City" : "Mumbai"    
}                        
my_address.popitem()     
print(my_address)        

The output is obtained as:

{'Street': 8, 'Town': 'Kharghar'} 

The del keyword deletes the item with the specified key name.

my_address = {            
    "Street" : 8,         
    "Town" : "Kharghar",  
    "City" : "Mumbai"     
}                         
del my_address["Town"]    
print(my_address)         

The output is obtained as:

{'Street': 8, 'City': 'Mumbai'}

The del keyword is also used to delete the entire dictionary.

my_address = {                
    "Street" : 8,             
    "Town" : "Kharghar",      
    "City" : "Mumbai"         
}                             
del my_address                
print(my_address)             

Printing the dictionary will generate an error as the dictionary no longer exists.

The clear() method returns  an empty dictionary.

my_address = {            
    "Street" : 8,         
    "Town" : "Kharghar",  
    "City" : "Mumbai"     
}                         
my_address.clear()        
print(my_address)         

The output is obtained as:

{}

The output shows that the dictionary is empty.

 

·         Looping through a dictionary:

A for loop is used to loop through a dictionary. Generally the return value is a key but there are methods to get values as well. The keys(), values() and items() methods can be used to get keys, values and key value pairs respectively.

my_address = {                
    "Street" : 8,             
    "Town" : "Kharghar",      
    "City" : "Mumbai"         
}                             
#default return value         
print("All the keys are:")    
for i in my_address:          
    print(i)                  
                              
#using values() method        
print("All the values are:")  
for i in my_address.values(): 
    print(i)                  
                              
#using keys() method          
print("All the keys are:"   
for i in my_address.keys():   
    print(i)                  
                              
#using items() method         
print("All the items are:")   
for i,j in my_address.items():
    print
(i,j)                

The output is obtained as:

All the keys are:         
Street                    
Town                      
City                      
All the values are:       
8                         
Kharghar                  
Mumbai                    
All the keys are:         
Street                    
Town                      
City                      
All the items are:        
Street 8                  
Town Kharghar             
City Mumbai               

 

·         Copying a dictionary:

There are two ways to copy a dictionary. First is to use the copy() method, second is to use the in-built dict() function.

my_address = {                                      
    "Street" : 8,                                   
    "Town" : "Kharghar",                            
    "City" : "Mumbai"                               
}                                                   
#using copy() method                                
your_address = my_address.copy()                    
print(your_address)                                 
                                                    
#using dict() function                              
your_adddress = dict(my_address)                    
print(your_address)                                 

The output is obtained as:

{'Street': 8, 'Town': 'Kharghar', 'City': 'Mumbai'}
{'Street': 8, 'Town': 'Kharghar', 'City': 'Mumbai'}


·         Nested dictionary:

A dictionary into a dictionary is called as Nested dictionary 

my_family = {                
    "mother" : {             
        "name" : "Sakshi",   
        "age" : 45           
    },                       
    "father" : {             
        "name" : "Suhas",    
        "age" :50            
    },                       
    "brother"              
        "name" : "Raj",      
        "age" : 23           
    },                       
}                            
print(my_family)             

The output is obtained as:

{'mother': {'name': 'Sakshi', 'age': 45},          'father': {'name': 'Suhas', 'age': 50}, 'brother': {'name': 'Raj', 'age': 23}}                       

Or you can also create three dictionaries and add to a new dictionary to make it nested.

mother = {                
        "name" : "Sakshi",
        "age" : 45        
    }                     
                          
father = {                
        "name" : "Suhas"
        "age" :50         
    }                     
                          
brother = {               
        "name" : "Raj",   
        "age" :23         
    }                     
my_family = {             
  "Mother" : mother,      
  "Father" : father,      
  "Brother" : brother     
}                         
print(my_family)          

The output is obtained as:

{'Mother': {'name': 'Sakshi', 'age': 45},          'Father': {'name': 'Suhas', 'age': 50}, 'Brother': {'name': 'Raj', 'age': 23}}                       

 

·         Dictionary methods:

Python offers a bunch of dictionary methods given below:

Method

Description

clear()

Removes all the elements from the dictionary

copy()

Returns a copy of the dictionary

fromkeys()

Returns a dictionary with the specified keys and value

get()

Returns the value of the specified key

items()

Returns a list containing a tuple for each key value pair

keys()

Returns a list containing the dictionary's keys

pop()

Removes the element with the specified key

popitem()

Removes the last inserted key-value pair

setdefault()

Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

update()

Updates the dictionary with the specified key-value pairs

values()

Returns a list of all the values in the dictionary

 

With this we come to an end of this article. Hope it was helpful. Do provide your feedback and ideas through comments, it would be highly appreciated. See you soon!

Keep coding and exploring new techs!! 


0 comments:

Post a Comment