ST JOSEPH’S SCHOOL
SUBJECT – COMPUTER SCIENCE
DICTIONARIES
Introduction to Dictionaries
Maps include the data type dictionary. A collection of keys and a set of values
are mapped in this situation. Items are keys and values pairs. Consecutive
entries are separated by commas, and a colon (:) separates a key from its
value. Dictionary entries are unordered, thus we might not receive the data in
the same order that we entered it when we first placed it in the dictionary.
Creating a Dictionary
The words entered are contained in curly brackets and are separated by
commas to form a dictionary. Each item is a pair of key values that are
separated by colons (:). The dictionary’s keys must be distinct and of any
immutable data type, such as an integer, text, or tuple. The values may be of
any data type and may be repeated.
Example –
>>> dict3 = {‘Mohan’:95,’Ram’:89,’Suhel’:92,’Sangeeta’:85}
>>> dict3
{‘Mohan’: 95, ‘Ram’: 89, ‘Suhel’: 92,’Sangeeta’: 85}
Accessing Items in a Dictionary
We have already seen how an approach known as indexing is used to retrieve
the elements of a sequence (string, list, and tuple). The keys in a dictionary
are used to access the objects rather than their indices or relative places.
Each key corresponds to a value and acts as an index.
Example –
>>> dict3 = {‘Mohan’:95,’Ram’:89,’Suhel’:92, ‘Sangeeta’:85}
>>> dict3[‘Ram’]
89
>>> dict3[‘Sangeeta’]
85
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 –
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 –
Example –
>>> dict1 = {‘Mohan’:95,’Ram’:89,’Suhel’:92,’Sangeeta’:85}
>>> 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 present in the dictionary and
returns True, else it returns False.
Example –
>>> 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.
Example –
>>> 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.
METHOD 1
>>> dict1 ={‘Mohan’:95,’Ram’:89,’Suhel’:92,’Sangeeta’:85}
>>> 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)
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Dictionary methods and Built-in functions
Python provides many functions to work on dictionaries.
len() - Returns the length or number of key: value pairs of the dictionary
passed as the argument.
Example –
>>> dict1 = {‘Mohan’:95,’Ram’:89,
‘Suhel’:92, ‘Sangeeta’:85}
>>> len(dict1)
4
dict() - Creates a dictionary from a sequence of key-value pairs.
Example –
pair1 = [(‘Mohan’,95),(‘Ram’,89),(‘Suhel’,92),(‘Sangeeta’,85)]
>>> pair1
[(‘Mohan’, 95), (‘Ram’, 89), (‘Suhel’,92), (‘Sangeeta’, 85)]
>>> dict1 = dict(pair1)
>>> dict1
{‘Mohan’: 95, ‘Ram’: 89, ‘Suhel’: 92,’Sangeeta’: 85}
keys() - Returns a list of keys in the dictionary.
Example –
>>> dict1 = {‘Mohan’:95, ‘Ram’:89,’Suhel’:92, ‘Sangeeta’:85}
>>> dict1.keys()
dict_keys([‘Mohan’, ‘Ram’, ‘Suhel’,’Sangeeta’])
values() - Returns a list of values in the dictionary.
Example –
>>> dict1 = {‘Mohan’:95, ‘Ram’:89,’Suhel’:92, ‘Sangeeta’:85}
>>> dict1.values()
dict_values([95, 89, 92, 85])
items() - Returns a list of tuples(key – value) pair
Example –
>>> dict1 = {‘Mohan’:95, ‘Ram’:89,’Suhel’:92, ‘Sangeeta’:85}
>>> dict1.items()
dict_items([( ‘Mohan’, 95), (‘Ram’,89), (‘Suhel’, 92), (‘Sangeeta’, 85)])
get() - Returns the value corresponding to the key passed as the argument.
Example –
>>> dict1 = {‘Mohan’:95, ‘Ram’:89,’Suhel’:92, ‘Sangeeta’:85}
>>> dict1.get(‘Sangeeta’)
85
update() - appends the key-value pair of the dictionary passed as the
argument to the key-value pair of the given dictionary.
Example –
>>> dict1 = {‘Mohan’:95, ‘Ram’:89,’Suhel’:92, ‘Sangeeta’:85}
>>> dict2 = {‘Sohan’:79,’Geeta’:89}
>>> dict1.update(dict2)
>>> dict1
{‘Mohan’: 95, ‘Ram’: 89, ‘Suhel’: 92,’Sangeeta’: 85, ‘Sohan’: 79, ‘Geeta’:89}
>>> dict2
{‘Sohan’: 79, ‘Geeta’: 89}
del() - Deletes the item with the given key To delete the dictionary from the
memory we write: del Dict_name
Example –
>>> dict1 = {‘Mohan’:95,’Ram’:89,’Suhel’:92, ‘Sangeeta’:85}
>>> del dict1[‘Ram’]
>>> dict1
{‘Mohan’:95,’Suhel’:92, ‘Sangeeta’: 85}
>>> del dict1 [‘Mohan’]
>>> dict1
{‘Suhel’: 92, ‘Sangeeta’: 85}
clear() - Deletes or clear all the items of the dictionary
Example –
>>> dict1 = {‘Mohan’:95,’Ram’:89,’Suhel’:92, ‘Sangeeta’:85}
>>> dict1.clear()
>>> dict1
{}