Class-XI CS
Unit-2: Computational thinking & Programming
Dictionary
Prepared By:
Mukesh Chourasia
PGT (Computer Science)
PM Shri Kendriya Vidyalaya No.2 CPE Itarsi
Dictionary
Syllabus:
Introduction: Definition, concept of key-value pairs
Dictionary Operations: creating, initializing, adding,
accessing, updating, deleting elements and traversing.
Dictionary methods & built-in functions: len(), dict(),
keys(), values(), items(), get(), update(), del(), del,
clear(), fromkeys(), copy(), pop(), popitem(),
setdefault(), max() and min(), sorted()
Dictionary: Introduction
Definition: A Dictionary is an unordered collection of elements
enclosed within curly brackets {}. It is a mapping data type with
elements of the form- key: value pairs and is mutable.
Example:
D={1:’Monday’, 2:’Tuesday’, 3:’Wednesday’,4:’Thursday’}
D={‘Name’:’Amit’, ‘Class’:11, ‘Section’:’B’, ‘Marks’:99.5}
Characteristics of a Dictionary
A Dictionary is an unordered collection of comma separated
items enclosed within curly brackets {}
It is a mapping data type. It is a mapping between a set of keys
and a set of values.
Items in a dictionary consists of key:value pairs.
Key and value are separated by : (colon)
The keys in the dictionary must be unique
The keys in the dictionary should be of any immutable data type,
i.e., number, string or tuple. The values can be of any data type.
Dictionaries are mutable which implies that the contents of the
dictionary can be changed after it has been created.
Dictionary Operations
Creating a dictionary
Initializing a dictionary
Adding a new element to a dictionary
Accessing elements in a dictionary
Updating/Modifying elements in a dictionary
Deleting elements from a dictionary
Checking for a key in dictionary
Traversing a dictionary
Creating an Empty Dictionary
Creating an empty dictionary
D ={}
print(D)
using dict() function
D=dict()
print(D)
Creating a Dictionary by direct Initialization
Example1:
D={‘Name’:’Amit’, ‘Class’:11, ‘Section’:’B’, ‘Marks’:99.5}
print(D)
Example2:
D={1:’Monday’, 2:’Tuesday’, 3:’Wednesday’, 4:’Thursday’}
print(D)
Initializing means-assigning value directly to a dictionary
Creating a Dictionary by direct Initialization
Example
Q. Create a Dictionary ‘Result’ with name of students as keys
and percentage of marks as values.
Sol:
Result={‘Ram’:85, ‘Shyam’:78, ‘Laxman’:75, ‘Sangeeta’:65}
print(Result)
Creating a Dictionary from User Input
Q. Create a Dictionary ‘Result’ with name of students as keys
and percentage of marks as values taking input from the user.
Sol:
Result={ }
n=input(“Enter the number of students: ”)
for i in range(n):
name=input(“Enter the name of the student: ”)
marks=int(input(“Enter the percentage of the student: ”))
Result[name]=marks
print(Result)
Adding New Elements to a Dictionary
Syntax:
D[Key] = value
D=dict() OR D={ }
D["one"]="keyboard"
D["two"]="Mouse"
D["three"]="printer"
D["Four"]="scanner"
print (D)
Note: New key:value pairs will be added to a dictionary if the key is not already
present in the dictionary.
Adding New Elements to a Dictionary
Example
Q. Given a dictionary:
D = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
Add a new student Meena with marks 78 to the above dictionary.
Sol:
D[‘Meena’]=78
print(D)
Accessing Elements in a Dictionary
The items of a dictionary are accessed via the keys. Each key
serves as the index and maps to a value.
Syntax:
print(D[Key])
Given a dictionary Age:
Age={‘Raman’:15, ‘Kishore’:16, ‘Priya’:17, ‘Deeksha’:16}
print(Age[‘Kishore’])
16
print(Age[‘Payal’])
Key error
Note: if the key is not present in the dictionary, key error occurs
Accessing Elements in a Dictionary
Example
Q. Given a dictionary Percent that maps names of the students
to respective marks in percentage
Percent = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
Write statements to print marks of – Ram and Shyam
Sol: print(Percent[‘Ram’])
89
print(Percent[‘Shyam’])
Key error
Note: if the key is not present in the dictionary, key error occurs
Update/Modify elements in a Dictionary
Dictionaries are mutable i.e. contents of the dictionary can be
changed after it has been created.
Syntax:
D[Key] = value
New key:value pairs will be added to a dictionary if the key is not
already present in the dictionary. If the key is already present in
the dictionary then its corresponding value will be modified.
Update/Modify elements in a Dictionary
Example
Q. Given a dictionary Age that maps names of the students to
their age.
Age={'Raman':15, 'Kishore':16, 'Priya':17, 'Deeksha':16}
Write statements to change the age of – Priya to 16
Sol: Age[‘Priya’]=16
print(Age)
Deleting elements from a Dictionary
del keyword is used for deleting a key:value pair from a dictionary.
Syntax:
del D[Key]
del keyword deletes a key: value pair from a dictionary if the key is
present otherwise returns a keyError
Deleting elements from a Dictionary
Example: Given a dictionary Age as shown below-
Write statement to remove ‘Priya’ from the dictionary
Sol.
del Age[‘Priya’]
print(Age)
Note: if the key is not present in the dictionary, key error occurs
Checking for a key in Dictionary
Membership Operators: in and not in
Syntax
print(Key in/not in D)
in – Returns True if the key is present in the dictionary otherwise
False.
not in - Returns True if the key is not present in the dictionary
otherwise False.
Checking for a key in Dictionary
Membership Operators: in and not in
Example
Given a dictionary
D= {'Mohan':95,'Ram':89,'Sohan':92, 'Sangeeta':85}
check the presence of ‘Sohan’ and ‘Radha’ in the above dictionary
Sol.
print(‘Sohan’ in D)
True
print(‘Radha’ in D)
False
print(92 in D)
False
print(‘Supriya’ not in D)
True
Dictionary Methods & Built-in Functions
Method Description Example
len() Returns the length or >>> D = {'Mohan':95,'Ram':89, 'Suhel':92, 'Sangeeta':85}
number of key: value >>> len(D)
pairs of the dictionary 4
passed as argument
dict() Creates a dictionary L = [('Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)]
from a sequence of >>> D = dict(L)
key-value pairs >>> D
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
keys() Returns a list of keys in >>> D = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}
the dictionary >>> D.keys()
dict_keys(['Mohan', 'Ram', 'Suhel', 'Sangeeta'])
values() Returns a list of values >>> D = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}
in the dictionary >>> D.values()
dict_values([95, 89, 92, 85])
items() Returns a list of >>> D = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}
tuples(key – value) pair >>> D.items()
dict_items([( 'Mohan', 95), ('Ram', 89), ('Suhel', 92),
('Sangeeta', 85)])
Dictionary Methods & Built-in Functions
Method Description Example
get() Returns the value >>> D = {'Mohan':95, 'Ram':89, 'Suhel':92,
corresponding to the key 'Sangeeta':85}
passed as argument. If the key >>> D.get('Sangeeta')
is not present in the 85
dictionary it will return None >>> D.get('Sohan')
None
update() Merging two dictionaries: >>> D1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
updates the dictionary with 'Sangeeta':85}
the key-value pair of the >>> D2 = {'Sohan':79,'Geeta':89}
dictionary passed as >>> D1.update(D2)
argument. >>> D1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85,
'Sohan': 79, 'Geeta': 89}
>>> D2
{'Sohan': 79, 'Geeta': 89}
del() deletes an entire dictionary >>> D = {'Mohan':95,'Ram':89, 'Suhel':92,
'Sangeeta':85}
>>> del(D)
>>>D
NameError: name ‘D’ is not defined
Dictionary Methods & Built-in Functions
Method Description Example
del keyword removes a key-value >>> del D['Mohan']
pair from the >>> D
dictionary based on {'Ram':89, 'Suhel': 92, 'Sangeeta': 85}
the key
clear() removes or clears >>> D = {'Mohan':95,'Ram':89, 'Suhel':92, 'Sangeeta':85}
all items of the >>> D.clear()
dictionary and >>> D
makes the {}
dictionary empty
fromkeys() returns a dictionary Syntax:
with the specified D.fromkeys(keys,value)
keys and values. >>>D={ }
>>>D.fromkeys([1,2,3],’a’)
>>>{1:’a’,2:’b’,3:’c’}
If values are not specified it defaults to None
>>>D.fromkeys([10,20,30])
>>>D
{10:None, 20:None, 30:None}
Dictionary Methods & Built-in Functions
Method Description Example
copy() This function returns a shallow copy of the using copy() method
dictionary, Syntax:
A copy is created with a new name and the newdict=originaldict.copy()
values are shared by the two copies.
>>>D={1:’Mon’,2:’Tue’,3:’Wed’}
changes made in one are not reflected in
another. >>>T=D.copy()
>>>T
{1:’Mon’,2:’Tue’,3:’Wed’}
>>>D[3]=’Thurs’
>>>D
{1:’Mon’,2:’Tue’,3:’Thurs’}
>>>T
{1:’Mon’,2:’Tue’,3:’Thurs’}
pop() If key is in the dictionary, this function Syntax:D.pop(key)
removes it and returns its value, else it >>>D={10:’a’,20:’b’,30:’c’,40:’d’}
returns KeyError. >>>D.pop(20)
‘b’
>>>D
{10:’a’,30:’c’,40:’d’}
Dictionary Methods & Built-in Functions
Method Description Example
popitem() This function removes and returns the last Syntax: D.popitem()
inserted (key, value) pair as tuple >>>D={10:’a’,20:’b’,30:’c’,40:’d’}
>>>D.popitem()
(40 , ’d’)
>>>D.popitem()
(30 , ’c’)
setdefault() If key is in the dictionary, this function Syntax: D.setdefault(key,value)
returns its value. If not, the insert key with a >>>D={10:’a’,20:’b’,30:’c’,40:’d’}
value of default is returned. It defaults to >>>D.setdefault(50,’s’)
None. ‘s’
>>>D
{10:’a’,20:’b’,30:’c’,40:’d’,50:’s’}
>>> D.setdefault(20,’p’)
‘b’
>>>D
{10:’a’,20:’b’,30:’c’,40:’d’,50:’s’}
min() Finds the key with minimum value in a >>>month={31:’Jan’,27:’Feb’,30:’Mar’
dictionary }
>>>min(month)
27
Dictionary Methods & Built-in Functions
Method Description Example
max() Finds the key with maximum value in a >>>month={31:’Jan’,27:’Feb’,30:’
dictionary. (For strings, ASCII values Mar’}
are used) >>>max(month)
31
>>>D={‘Apple’:50,’Mango’:80,’Or
ange’:65}
>>>max(D)
‘Orange’
sorted() Returns a list of keys in ascending >>>month={31:’Jan’,27:’Feb’,30:’
order by default. for descending order, Mar’}
reverse=True >>>sorted(month)
[27,30,31]
>>>
sorted(month,reverse=True)
[31,30,27]
Solved Examples
Q1. 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 (e) Check if 7 is present or not
(b) Display the values (f) Check if 2 is present or not
(c) Display both keys & values (g) Retrieve the value corresponding to the key 9
(d) Find the length of the dictionary (h) Delete the item from the dictionary
corresponding to the key 9
Sol. ODD = {1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
(a) print(ODD.keys())
(b) print(ODD.values())
(c) print(ODD.items())
(d) print(len(ODD))
(e) print(7 in ODD)
(f) print(2 in ODD)
(g) print(ODD[9])
(h) ODD.del(9) or del ODD[9]
Solved Examples
Q2. Consider the following dictionary stateCapital:
stateCapital = {"Andhra Pradesh":"Hyderabad", "Bihar": "Patna", "Maharashtra“ :
“Mumbai“ , "Rajasthan“ : "Jaipur"}
Find the output of the following statements:
i. print(stateCapital.get("Bihar")) v. print(len(stateCapital))
ii. print(stateCapital.keys()) vi print("Maharashtra" in stateCapital)
iii. print(stateCapital.values()) vii. print(stateCapital.get("Assam"))
iv. print(stateCapital.items()) viii. del stateCapital["Andhra Pradesh"]
print(stateCapital)
Sol. i) ‘Patna’
ii) dict_keys(['AndhraPradesh', 'Bihar', 'Maharashtra', 'Rajasthan'])
iii) dict_values(['Hyderabad', 'Patna', 'Mumbai', 'Jaipur'])
iv) dict_items([('Andhra Pradesh', 'Hyderabad'), ('Bihar', 'Patna'), ('Maharashtra',
'Mumbai'), ('Rajasthan', 'Jaipur')])
v) 4
vi) True
vii) None
viii) {'Bihar': 'Patna', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur'}
Solved Examples
Q3. Create a dictionary Friends with your friends’ names as keys and their Phone
Numbers as values. Perform the following operations on the dictionary:
a) Display the name and phone number of all your friends
b) Add a new key-value pair in this dictionary and display the modified dictionary
c) Delete a particular friend from the dictionary
d) Modify the phone number of an existing friend
e) Check if a friend is present in the dictionary or not
f) Display the dictionary in sorted order of names
Sol. Friends={‘Kishore’:’5827415268’, ‘Saksham’ : ’8595854584’, ‘Dheeraj’:
’8794562541’, ‘Jitendra’: ’7845126589’ }
a) print(Friends.items()) OR print(Friends)
b) Friends[‘Gagan’] = ‘9868587457’
c) del Friends[‘Jitendra’] OR Friends.pop(‘Jitendra’)
d) Friends[‘Dheeraj’] = ‘7849562541’
e) print(‘Kishore’ in Friends)
f) print(sorted(Friends))