D.
ANUJESUS ME,MSc,BE,BEd,DSc
PGT - COMPUTER, DCIRS
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. Items in dictionaries are ordered, so we will get
back the data in the same order in which we had entered the data initially in the dictionary.
10.1.1 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 10.4
#dict1 is an empty Dictionary created #curly braces are used for dictionary
>>> dict1 = {}
>>> 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}
10.1.2 Accessing Items in a Dictionary
We have already seen that the items of a 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
D. ANUJESUS ME,MSc,BE,BEd,DSc
PGT - COMPUTER, DCIRS
>>> 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. So the order of items does not matter. If the key is not present in the
dictionary we get KeyError.
10.2 DICTIONARIES ARE MUTABLE
Dictionaries are mutable which implies that the contents of the dictionary can be changed after
it has been created.
10.2.1 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}
10.2.2 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}
10.3 Dictionary Operations
10.3.1 Membership
The membership operator in checks if the key is present in 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
D. ANUJESUS ME,MSc,BE,BEd,DSc
PGT - COMPUTER, DCIRS
10.4 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]) Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Method 2
>>> for key,value in [Link](): print(key,':',value)
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
10.5 Dictionary methods and Built-in functions
Python provides many functions to work on dictionaries. Table 10.2 lists some of
the commonly used dictionary methods.
Table 10.2 Built-in functions and methods for dictionary
Method Description Example
len() Returns the length or number >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92,
of key: value pairs of the 'Sangeeta':85}
dictionary passed as the
>>> len(dict1) 4
argument
dict() Creates a dictionary from a pair1 = [('Mohan',95),('Ram',89),
sequence of key-value pairs ('Suhel',92),('Sangeeta',85)]
>>> pair1
[('Mohan', 95), ('Ram', 89), ('Suhel',
92), ('Sangeeta', 85)]
>>> dict1 = dict(pair1)
>>> dict1
D. ANUJESUS ME,MSc,BE,BEd,DSc
PGT - COMPUTER, DCIRS
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,
'Sangeeta': 85}
keys() Returns list of keys in >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
a the 'Sangeeta':85}
dictionary
>>> [Link]()
dict_keys(['Mohan', 'Ram', 'Suhel', 'Sangeeta'])
values() Returns a list of values in >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
'Sangeeta':85}
the dictionary
>>> [Link]() dict_values([95, 89, 92, 85])
items() Returns a list of tuples(key – >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
'Sangeeta':85}
value) pair
>>> [Link]()
dict_items([( 'Mohan', 95), ('Ram',
89), ('Suhel', 92), ('Sangeeta', 85)])
get() Returns the value >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
corresponding to the key 'Sangeeta':85}
passed as the argument
>>> [Link]('Sangeeta') 85
>>> [Link]('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,
the dictionary passed as the 'Sangeeta':85}
argument to the key-value pair
>>> dict2 = {'Sohan':79,'Geeta':89}
of the given dictionary
>>> [Link](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 >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92,
key 'Sangeeta':85}
To delete the dictionary from >>> del dict1['Ram']
the
D. ANUJESUS ME,MSc,BE,BEd,DSc
PGT - COMPUTER, DCIRS
memory we write: >>> dict1
del Dict_name {'Mohan':95,'Suhel':92, 'Sangeeta': 85}
>>> 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,
the dictionary 'Sangeeta':85}
>>> [Link]()
>>> dict1
{}
10.6 Manipulating Dictionaries
In this chapter, we have learnt how to create a dictionary and apply various methods to
manipulate it. The following programs show the application of those manipulation methods on
dictionaries.
D. ANUJESUS ME,MSc,BE,BEd,DSc
PGT - COMPUTER, DCIRS
Program 10-5 Create a dictionary ‘ODD’ of odd numbers between 1 and 10, where the key is
the decimal 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
>>> [Link]() dict_keys([1, 3, 5, 7, 9])
(b) Display the values
>>> [Link]()
dict_values(['One', 'Three', 'Five', 'Seven', 'Nine'])
(c) Display the items
>>> [Link]()
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
D. ANUJESUS ME,MSc,BE,BEd,DSc
PGT - COMPUTER, DCIRS
False
(g) Retrieve the value corresponding to the key 9
>>> [Link](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'}
Program 10-6 Write a program to enter names of employees and their salaries as input and
store them in a dictionary.
#Program 10-6
#Program to create a dictionary which stores names of the employee #and their salary
num = int(input("Enter the number of employees whose data to be stored: "))
count = 1
employee = dict() #create an empty dictionary while count <= num:
name = input("Enter the name of the Employee: ") salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1 print("\n\nEMPLOYEE_NAME\tSALARY") for k in employee:
print(k,'\t\t',employee[k])
Output:
Enter the number of employees to be stored: 5 Enter the name of the Employee: 'Tarun' Enter
the salary: 12000
Enter the name of the Employee: 'Amina' Enter the salary: 34000
Enter the name of the Employee: 'Joseph' Enter the salary: 24000
Enter the name of the Employee: 'Rahul' Enter the salary: 30000
Enter the name of the Employee: 'Zoya' Enter the salary: 25000
EMPLOYEE_NAME SALARY
'Tarun' 12000
'Amina' 34000
'Joseph' 24000
D. ANUJESUS ME,MSc,BE,BEd,DSc
PGT - COMPUTER, DCIRS
'Rahul'30000
'Zoya' 25000
Program 10-7 Write a program to count the number of times a character appears in a given
string.
#Program 10-7
#Count the number of times a character appears in a given string
st = input("Enter a string: ")
dic = {} #creates an empty dictionary for ch in st:
if ch in dic: #if next character is already in the dictionary dic[ch] += 1
else:
dic[ch] = 1 #if ch appears for the first time
for key in dic:
print(key,':',dic[key])
Output:
Enter a string: HelloWorld H : 1
e:1
l:3
o:2
W:1
r:1
d:1
Program 10-8 Write a function to convert a number entered by the user into its corresponding
number in words. For example, if the input is 876 then the output should be ‘Eight Seven Six’.
# Program 10-8
# Write a function to convert number into corresponding number in # words
def convert(num):
#numberNames is a dictionary of digits and corresponding number #names
numberNames = {0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',\
5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine'}
D. ANUJESUS ME,MSc,BE,BEd,DSc
PGT - COMPUTER, DCIRS
result = '' for ch in num:
key = int(ch) #converts character to integer value = numberNames[key]
result = result + ' ' + value return result
num = input("Enter any number: ") #number is stored as string result = convert(num)
print("The number is:",num) print("The numberName is:",result)
Output:
Enter any number: 6512 The number is: 6512
The numberName is: Six Five One Two
Exercise
1. Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
print([Link](45))
print([Link](45))
print(tuple1 + tuple2)
print(len(tuple2))
print(max(tuple1))
print(min(tuple1))
print(sum(tuple2))
print(sorted(tuple1)) print(tuple1)
2. Consider the following dictionary
stateCapital: stateCapital = {"AndhraPradesh":"Hyderabad", "Bihar":"Patna",
"Maharashtra":"Mumbai", "Rajasthan":"Jaipur"}
Find the output of the following statements:
print([Link]("Bihar"))
D. ANUJESUS ME,MSc,BE,BEd,DSc
PGT - COMPUTER, DCIRS
print([Link]())
print([Link]())
print([Link]())
print(len(stateCapital))
print("Maharashtra" in stateCapital)
print([Link]("Assam"))
del stateCapital["Rajasthan"] print(stateCapital)
3. “Lists and Tuples are ordered”. Explain.
4. With the help of an example show how can you return more than one value from a
function.
5. What advantages do tuples have over lists?
6. When to use tuple or dictionary in Python. Give some examples of programming
situations mentioning their usefulness.
7. Prove with the help of an example that the variable is rebuilt in case of immutable data
types.
8. TypeError occurs while statement 2 is running. Give reason. How can it be corrected?
>>> tuple1 = (5) #statement 1
>>> len(tuple1) #statement 2
Programming Problems
1. Write a program to read email IDs of n number of students and store them in a tuple.
Create two new tuples, one to store only the usernames from the email IDs and second to store
domain names from the email IDs. Print all three tuples at the end of the program. [Hint: You
may use the function split()]
2. Write a program to input names of n students and store them in a tuple. Also, input a
name from the user and find if this student is present in the tuple or not.
We can accomplish these by:
(a) writing a user defined function
(b) using the built-in function
3. Write a Python program to find the highest 2 values in a dictionary.
4. Write a Python program to create a dictionary from a string.
Note: Track the count of the letters from the string.
D. ANUJESUS ME,MSc,BE,BEd,DSc
PGT - COMPUTER, DCIRS
Sample string : 'w3resource'
Expected output : {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}
5. Write a program to input your friends’ names and their Phone Numbers and store them
in the dictionary as the key-value pair. Perform the following operations on the dictionary:
• Display the name and phone number of all your friends
• Add a new key-value pair in this dictionary and display the modified dictionary
• Delete a particular friend from the dictionary
• Modify the phone number of an existing friend
• Check if a friend is present in the dictionary or not
• Display the dictionary in sorted order of names
Case Study-based Question
For the SMIS System given in Chapter 5, let us do the following:
Write a program to take in the roll number, name and percentage of marks for n students of
Class X. Write user defined functions to
• accept details of the n students (n is the number of students)
• search details of a particular student on the basis of roll number and display result
• display the result of all the students
• find the topper amongst them
• find the subject toppers amongst them
(Hint: use Dictionary, where the key can be roll number and the value is an immutable data
type containing name and percentage) Let’s peer review the case studies of others based on
the parameters given under “DOCUMENTATION TIPS” at the end of Chapter 5 and provide a
feedback to them.
Case Study-based Questions
1. A bank is a financial institution which is involved in borrowing and lending of money.
With advancement in technology, online banking, also known as internet banking allows
customers of a bank to conduct a range of financial transactions through the bank’s website
anytime, anywhere. As part of initial investigation you are suggested to
• collect a bank’s application form. After careful analysis of the form, identify the
information required for opening a savings account. Also enquire about the rate of interest
offered for a saving account.
• The basic two operations performed on an account are Deposit and Withdrawal. Write a
menu driven program that accepts either of the two choices of Deposit and Withdrawal,
D. ANUJESUS ME,MSc,BE,BEd,DSc
PGT - COMPUTER, DCIRS
then accepts an amount, performs the transaction and accordingly displays the balance.
Remember, every bank has a requirement of minimum balance which needs to be taken
care of during withdrawal operations. Enquire about the minimum balance required in
your bank.
• Collect the interest rates for opening a fixed deposit in various slabs in a savings bank
account. Remember, rates may be different for senior citizens.
Finally, write a menu driven program having the following options (use functions and
appropriate data types):
• Open a savings bank account
• Deposit money
• Withdraw money
• Take details, such as amount and period for a Fixed Deposit and display its maturity
amount for a particular customer.
2. Participating in a quiz can be fun as it provides a competitive element. Some
educational institutes use it as a tool to measure knowledge level, abilities and/or skills of their
pupils either on a general level or in a specific field of study. Identify and analyse popular quiz
shows and write a Python program to create a quiz that should also contain the following
functionalities besides the one identified by you as a result of your analysis.
• Create an administrative user ID and password to categorically add, modify, delete a
question
• Register the student before allowing her or him to play a quiz
• Allow selection of category based on subject area
• Display questions as per the chosen category
• Keep the score as the participant plays
• Display the final score
3. Our heritage monuments are our assets. They are a reflection of our rich and glorious
past and an inspiration for our future. UNESCO has identified some of Indian heritage sites as
World heritage sites. Collect the following information about these sites:
• What is the name of the site?
• Where is it located?
▪ District
▪ State
• When was it built?
D. ANUJESUS ME,MSc,BE,BEd,DSc
PGT - COMPUTER, DCIRS
• Who built it?
• Why was it built?
• Website link (if any). Write a Python program to
• create an administrative user ID and password to add, modify or delete an entered
heritage site in the list of sites
• display the list of world heritage sites in India
• search and display information of a world heritage site entered by the user
• display the name(s) of world heritage site(s) on the basis of the state input by the user.
4. Every mode of transport utilises a reservation system to ensure its smooth and efficient
functioning. If you analyse you would find many things in common. You are required to
identify any one mode of transportation and prepare a reservation system for it. For example,
let us look at the Railway reservation system we talked about earlier. The complex task of
designing a good railway reservation system is seen as designing the different components of
the system and then making them work with each other efficiently. Possible sub- systems are
shown in Figure 1. Each of them may be modelled using functions. Write a python code to
automate the reservation needs of the identified mode of transport.
Trains' information Reservation information Information about
staff, security,
— days, timings, — booking open or close, railway
stations, classes and available or waiting List, infrastructure
births cancellation and refund
Other details about
Food service Billing service
railways
Figure 1: Railway rese reservation system