0% found this document useful (0 votes)
33 views11 pages

Chapter-13 Dictionaries

Chapter 13 introduces dictionaries in Python, which are mutable data types that store key-value pairs. It covers how to create, access, modify, and perform operations on dictionaries, including membership checks and traversing items. The chapter also provides examples of common dictionary methods and practical exercises for manipulating dictionaries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views11 pages

Chapter-13 Dictionaries

Chapter 13 introduces dictionaries in Python, which are mutable data types that store key-value pairs. It covers how to create, access, modify, and perform operations on dictionaries, including membership checks and traversing items. The chapter also provides examples of common dictionary methods and practical exercises for manipulating dictionaries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Chapter 13 - Introduction to 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

get() Returns the value >>> dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85}


corresponding >>> dict1.get('Sangeeta')
to the key passed as the 85
argument >>> dict1.get('Sohan')
If the key is not present in the >>>
dictionary it will return None
update() appends the key-value pair of >>> dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85}
the dictionary passed as the >>> dict2 = {'Sohan':79,'Geeta':89}
argument to the key-value pair >>> dict1.update(dict2)
of the given dictionary >>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85, 'Sohan': 79, 'Geeta': 89}
>>> dict2
{'Sohan': 79, 'Geeta': 89}
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

>>> ODD = {1:'One', 3:'Three', 5:'Five', 7:'Seven', 9:'Nine'}


>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven', 9: 'Nine'}
(a) Display the keys
>>> ODD.keys()
dict_keys([1, 3, 5, 7, 9])
(b) Display the values
>>> ODD.values()
dict_values(['One', 'Three', 'Five', 'Seven', 'Nine'])
(c) Display the items
>>> ODD.items()
dict_items([(1, 'One'), (3, 'Three'), (5, 'Five'), (7, 'Seven'),(9, 'Nine')])
(d) Find the length of the dictionary
>>> len(ODD)
5
(e) Check if 7 is present or not
>>> 7 in ODD
True
(f) Check if 2 is present or not
>>> 2 in ODD
False
(g) Retrieve the value corresponding to the key 9
>>> ODD.get(9)
'Nine‘
(h) Delete the item from the dictionary corresponding to the key 9
>>> del ODD[9]
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven'}
2. Write a program to enter names of employees and their salaries as input and store them in a dictionary.
emp= dict()
n = int(input("How many employees data u want to take"))
for i in range(0,n):
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
emp[name] = salary
for k in emp:
print(k,emp[k])
output
Enter the number of employees whose data to be stored: 3
Enter the name of the Employee: 101
Enter the salary: 20000
101 20000
Enter the name of the Employee: 102
Enter the salary: 40000
101 20000
102 40000
Enter the name of the Employee: 104
Enter the salary: 30000
101 20000
102 40000
104 30000
3.Write a program to input n employee names and their phone numbers to store it in a dictionary as key:value pair. Input a
name to search and display its phone no if found in dictionary otherwise display an error message.
emp=dict()
n = int(input("How many students? "))
for i in range(0,n):
name= input("Enter name of employee")
phone=input("Enter phone no:")
emp[name]=phone
nm=input("Enter name to search")
if nm in emp:
print("Phone no of",nm,"is",emp[nm])
else:
print("Employee name not found")
Ouput:
How many students? 3
Enter name of employeeRahul
Enter phone no:9897280816
Enter name of employeeTina
Enter phone no:7345617820
Enter name of employeeSam
Enter phone no:8098761234
Enter name to searchTina
Phone no of Tina is 7345617820

You might also like