Chapter-13 Dictionaries
Chapter-13 Dictionaries
The data type dictionary fall under mapping. It is a mapping between a set of keys and a set of values. The key-value pair
is called an item. A key is separated from its value by a colon(:) and consecutive items are separated by commas.
Creating a Dictionary
To create a dictionary, the items entered are separated by commas and enclosed in curly braces. Each item is a key value
pair, separated through colon (:). The keys in the dictionary must be unique and should be of any immutable data type,
i.e., number, string or tuple. The values can be repeated and can be of any data type.
Example
>>> dict1 = {} #dict1 is an empty Dictionary created
>>> dict1
{}
#dict2 is an empty dictionary created using built-in function
>>> dict2 = dict()
>>> dict2
{}
#dict3 is the dictionary that maps names of the students to respective marks in percentage
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict3
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
Accessing Items in a Dictionary
Sequence (string, list and tuple) are accessed using a technique called indexing. The items of a dictionary are accessed
via the keys rather than via their relative positions or indices. Each key serves as the index and maps to a value.The
following example shows how a dictionary returns the value corresponding to the given key:
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict3['Ram']
89
>>> dict3['Sangeeta']
85
#the key does not exist
>>> dict3['Shyam']
KeyError: 'Shyam'
In the above examples the key 'Ram' always maps to the value 89 and key 'Sangeeta' always maps to the value 85. If the
key is not present in the dictionary we get KeyError.
Dictionaries are Mutable
Dictionaries are mutable which implies that the contents of the dictionary can be changed after it has been created.
Adding a new item
We can add a new item to the dictionary as shown in the following example:
>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}
>>> dict1['Meena'] = 78
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85, 'Meena': 78}
Modifying an Existing Item
The existing dictionary can be modified by just overwriting the key-value pair. Example to modify a given item in the
dictionary:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
#Marks of Suhel changed to 93.5
>>> dict1['Suhel'] = 93.5
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5,'Sangeeta': 85}
Dictionary Operations
Membership
The membership operator in checks if the key is presentin the dictionary and returns True, else it returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> 'Suhel' in dict1
True
The not in operator returns True if the key is not present in the dictionary, else it returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> 'Suhel' not in dict1
False
Traversing a Dictionary
We can access each item of the dictionary or traverse a dictionary using for loop.
>>> dict1 ={'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
Method 1
for key in dict1:
print(key,':',dict1[key])
output
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Method 2
for key,value in dict1.items():
print(key,':',value)
output
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Dictionary methods and Built-in functions
Python provides many functions to work on dictionaries. some of the commonly used dictionary methods are
METHOD DESCRIPTION EXAMPLE
len() Returns the length or number of >>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
key: value pairs of the dictionary >>> len(dict1)
4
dict() Creates a dictionary from a pair1 = [('Mohan',95),('Ram',89),('Suhel',92),('Sangeeta',85)]
sequence of key-value pairs >>> pair1
[('Mohan', 95), ('Ram', 89), ('Suhel',92), ('Sangeeta', 85)]
>>> dict1 = dict(pair1)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85}
key() Returns a list of keys in the >>> dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85}
dictionary >>> dict1.keys()
dict_keys(['Mohan', 'Ram', 'Suhel','Sangeeta‘])
values() Returns a list of values in the >>> dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85}
dictionary >>> dict1.values()
dict_values([95, 89, 92, 85])
items() Returns a list of tuples(key – >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}
value) pair >>> dict1.items()
dict_items([( 'Mohan', 95), ('Ram',89), ('Suhel', 92), ('Sangeeta', 85)])
METHOD DESCRIPTION EXAMPLE
del() Deletes the item with the given >>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
key >>> del dict1['Ram']
To delete the dictionary from the >>> dict1
memory we write: {'Mohan':95,'Suhel':92, 'Sangeeta': 85}
del Dict_name >>> del dict1 ['Mohan']
>>> dict1
{'Suhel': 92, 'Sangeeta': 85}
>>> del dict1
>>> dict1
NameError: name 'dict1' is not defined
clear() Deletes or clear all the items of >>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
the dictionary >>> dict1.clear()
>>> dict1
{}
Manipulating Dictionaries
1.Create a dictionary ‘ODD’ of odd numbers between 1 and 10, where the key is number and the value is the corresponding
number in words. Perform the following operations on this dictionary:
(a) Display the keys
(b) Display the values
(c) Display the items
(d) Find the length of the dictionary
(e) Check if 7 is present or not
(f) Check if 2 is present or not
(g) Retrieve the value corresponding to the key 9
(h) Delete the item from the dictionary corresponding to the key 9