Xi Cs Unit-2 Dictionary
Xi Cs Unit-2 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
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)
Example
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
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
Note: if the key is not present in the dictionary, key error occurs
Checking for a key in Dictionary
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])
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))