0% found this document useful (0 votes)
55 views68 pages

Dictionary in Python

The document provides a comprehensive overview of Python dictionaries, including their creation, manipulation, and traversal. It explains the syntax for creating dictionaries, the importance of key-value pairs, and how to access and update elements. Additionally, it covers dictionary operators, user input handling, and various programming examples demonstrating dictionary usage.

Uploaded by

JEAN
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)
55 views68 pages

Dictionary in Python

The document provides a comprehensive overview of Python dictionaries, including their creation, manipulation, and traversal. It explains the syntax for creating dictionaries, the importance of key-value pairs, and how to access and update elements. Additionally, it covers dictionary operators, user input handling, and various programming examples demonstrating dictionary usage.

Uploaded by

JEAN
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/ 68

Dictionary In Python

Dictionary Data Type


 Python Dictionary is collection of elements where each
element is a key-value pair.
 The Dictionary object can be created by placing each
element inside curly braces where each element is
separated by comma (,).
Syntax :
Dictionary_object = {key:value, key:value:……}
Example : studdict = {1:”Ram”,2:”Shyam”,3:”Asha”}
 Dictionary is mutable i.e new element can be added and
value of an existing element can be changed.
Creation Of Dictionary Object
A Dictionary object can be created by placing each element inside curly
braces where each element is separated by comma (,). Each element of
a dictionary is a key:value pair
Syntax : Dictionary_name = {key:value, key:value:……}
Example : studdict = {1:”Ram”,2:”Shyam”,3:”Asha”}
 Each element of a dictionary is key:value pair where each key is
separated from it’s value by a colon (:). Each key map to a value.
 Keys are unique within a dictionary while values may not be.
 The keys of a dictionary must be of an immutable data type such
as string, numbers or tuples. The value of a dictionary can be of
any data type.
 The keys of a dictionary must be of immutable datatype. When a
mutable type of key is assigned to a dictionary object Python will
result TypeError.
Creation Of Dictionary Object
Creation Of Empty Dictionary Object
An empty dictionary can be created by assigning dictionary object to a set of curly braces
{} Or by using the built-in method dict() .
Syntax : Dictionary_name = {} or Dictionary_name = dict()
Example : dict = {} or d1 = dict()
Assigning Values to Dictionary Object
The empty dictionary object can be assigned with literals using the following syntax.
Syntax : dictionary object[key] = value
Example : >>> d3 = {} {1:”Shreya”}
>>> d3[1] = “Shreya" #Where 1 is key and Shreya is value
>>>d3
The dict() method can be used to initialize object by giving a set of keys and value pair as
argument to dict(). The key and value pair can be given either as a list or as a tuple.
Example : #key:value pair given as list
>>> st1 = dict([[1, "Shreya"],[2,"Rajesh"]])
>>> st1
{1: 'Shreya', 2: 'Rajesh'}
>>> st2 = dict(((3, "Reyan"),(4,"Raji"))) #key:value pair given as tuple
>>> st2
{3: 'Reyan', 4: 'Raji'}
Creation Of Dictionary Object
Creation Of Dictionary Object taking user Input within a loop
For creating a dictionary objects user input can be taken inside a loop. The
key and value from user and assigned to the object using the
Syntax : dictionary _name[key] = value
Example : Write a program to create a dictionary containing admission
number as key and name as values for “n” number of
students. Accept n from user. Display the dictionary
Program : stud={ } #Empty dictionary created
n = int(input("enter mumber of students - "))
for i in range(n):
admno = input("enter admission No - ")
name = input("enter name -")
stud[admno] = name
print(stud) #Displaying dictionary
Creation Of Dictionary Object
Syntax : dictionary _name[key] =[values]
Where the value part of the dictionary object is represented as a list
Program : stud={ } #Empty dictionary created
n=int(input("enter mumber of students - "))
for i in range(n):
admno = input("enter admission No - ")
name = input("enter name -")
m1=int(input(“marks1”)
m2=int(input(“marks2”)
m3=int(input(“marks3”)
TM=m1+m2+m3
per=TM/3
if per>=90: {101:[“a”,45,43,56,280,90,’a’]}
g=“A”
else:
g=“B”
stud[admno] = [name , m1,m2,m3,TM,per,g]
print(stud) #Displaying dictionary
Dictionary Operators
The ==/!= and in/not in operators can be used with Dictionary objects. The
concatenation operator (+) and repetition operator (*) can not be used with
Dictionary objects.
== and != Operator
Two dictionary objects can be compared for equality by using == and !=
operator. When two dictionary objects are same, == operator returns True,
Otherwise it returns False.
The != operator returns True if both objects are not same and returns False if
both are same
Example : >>> d1={1:“Rashi",2:“Anush",3:"rakesh"}
>>> d2={1:“Rashi",2:“Anush",3:"rakesh"}
>>> d1== d2
True
>>> d1 != d2
False
No other relational operator like >, <, >= and <= can be used with dictionary
object.
Dictionary Operators
in and not in Operator
The in operator checks whether a particular key value is present in the
dictionary or not. It returns True if the element appears in the
dictionary, otherwise it returns False.
Example : >>> d1={1:"Rahul", 2:"seema", 3:"Rashi"}
>>> 3 in d1
True
>>> "Rahul“ in d1
The not in operator returns True if the given key is not present in the
dictionary, otherwise it returns False
Example : >>> 13 not in d1
True
>>> 3 not in d1
False
Both in and not in operators can be used to a dictionary only to check the
existence of keys only
Accessing elements in a dictionary
For accessing element in a dictionary, the corresponding key is enclosed in square
bracket and the dictionary object with the key value in square bracket gives the
corresponding value.
The dictionary operation that takes a key and finds the corresponding value, is known
as Lookup
The values of a dictionary are accessed through the keys rather than their relative
positions or index. Each key of a dictionary serves as the index and maps to it’s
corresponding value.
Example : >>> d1 = {1 : "Rahul",2 : "Seema",3 : "Rashi"}
>>> d1[1]
'Rahul’
Updating elements in a dictionary
A dictionary object can be modified by modifying existing key-value pair .
Syntax: dictionary_name[key] = value
Example: tinydict={'name': 'john','code':6734, 'dept': 'admin',’basic’:5000}
tinydict[‘dept’] = ’Fin’
{'name': 'john','code':6734, 'dept': ‘Fin',’basic’:5000}
print(tinydict[‘a’])
When an attempt is made to access a Dictionary element with a key, which is not
existing dictionary object, Python will result keyError.
Traversing a dictionary Object
Traversing operation in a dictionary means accessing each element / item of a dictionary Object.
Traversing dictionary Object an be done using for loop.
Traversing Dictionary using loop
The in operator used with a for loop can be used to traverse each element of a dictionary object. The in
operator access key of each element of the dictionary object.
Syntax : for <key> in <Dictionary object>:
process each item
Once the key of each dictionary object is accessed, then using the syntax dictionary_object[key], each
element can be processed.
Example : WAP to input students details of a dictionary object with roll no as key and name as
value. Count the number of students
Program : stud = { } #Empty dictionary created
while True:
rno = input("enter Roll No - ")
stud[rno]=input(‘enter name’)
ans = input(“Want to Enter another ")
if ans in "Nn“:
break
ctr = 0
for rno in stud:
print(rno,“\t\t“,stud[rno])
ctr += 1
print(“Total No. of students – “,ctr)
Traversing a dictionary Object
Example : Write a program to create a dictionary containing roll
number as key and percentage as values for “n” number of
students. Display the no. of students scoring above 80%
Program : stud={ } Empty dictionary created
n=int(input("enter number of students - "))
for i in range(n):
rno = input("enter Roll No - ")
stud[rno] = float(input(“Enter percentage –“))
ctr = 0
for r in stud:
if stud[r] > 80:
ctr+=1
print(“No. of students scoring percentage above 80 – “,ctr)
Traversing a dictionary Object
Example : Write a program to create a dictionary containing employee no
as key and salary as values for “n” number of employees. Search
and Display the salary of an employee for a user given employee
no.
Program : emp = {}
n, i = int(input("Enter no of employees")),1
while i<=n:
eno = input("Enter name")
sal = float(input("Enter basic"))
emp[eno] = sal
i += 1
sno = input("enter employee no to be searched")
if sno in emp:
print(“Salary of “,sno -, “ - “,emp[sno])
else:
print(“Record not found")
Traversing a dictionary Object
Example : Write a program to create a dictionary containing product
id as key and product name as values for “n” number of
products. Search and Display the details of a user given
product name.
Program : d2 = {}
n = int(input("Enter number of elements"))
for i in range(n):
pno = int(input("Enter product id"))
d2[pno] = input("Enter pname")
sname = input("Enter name of product to be searched")
found=0
for pno in d2:
if d2[pno] == sname:
print("productname",d2[pno],"has",pno,"product id")
found=1
if found== 0:
Traversing a dictionary Object
Example : Write a program to input names of ‘n’ countries as key field
and their capital and currency in the form of a list as it’s value.
Search and display details for a particular user given country.
Program : dict = {}
n = int(input("Enter number of countries"))
for i in range(n):
cname=input("Enter country name")
cap=input("Enter capital")
currency=input("Enter currency")
dict[cname]=[cap,currency] # value as a list assigned
sname = input("Enter country name to search - ")
if sname in dict:
print("Name found in dictionary")
print(details of “,sname,” - “,dict[sname])
else:
print("Country name not found")
Traversing a dictionary Object
Example : Write a program to create a dictionary a key:value pair for “n”
number of elements . Check and display whether the dictionary
with different keys have same values or not. Display appropriate
message.
Program : d1 = {}
n = int(input("Enter no of elements"))
for i in range(n):
key = int(input("Enter key"))
d1[key] = eval(input("Enter value"))
for k in d1:
cnt = 0
for k1 in d1:
if d1[k] == d1[k1]:
cnt+=1
if cnt > 1:
break
if cnt > 1:
print(" keys have same value")
else:
print("No keys have same values")
Traversing a dictionary Object
Example : Write a program to create a dictionary containing
admission number as key and name as values for “n”
number of students. Remove the element matching
with the user given admission number
Program : d1,d2 = {},{}
n = int(input("Enter number of elements"))
for i in range(n):
admno=int(input("Enter admission number"))
name=input("Enter name")
d1[admno]=name
dano = int(input("Enter the admission no to be deleted - "))
for an in d1:
if an != dano:
d2[an]=d1[an]
print(“Original dictionary",d1)
print(“Edited dictionary",d2)
Traversing a dictionary Object
Example : Write a Python program to input the school name as key field
and area as value in a dictionary. Prepare an area-wise
frequency table and store it in another dictionary where area
will be the key field and frequency will be the value.
Program : s = {}
fs = {}
n = int(input("Enter no. of schools-"))
for i in range(n):
nm = input("Enter school name-")
s[nm] = input("area -")
for sn in s:
ctr = 0
for sn1 in s:
if s[sn] == s[sn1]:
ctr += 1
if s[sn] not in fs:
nk = s[sn]
fs[nk] = ctr
print(fs)
Traversing a dictionary Object
Example : Write a Python program to input the school name as key field
and area as value in a dictionary. Prepare an area-wise
frequency table and store it in another dictionary where area
will be the key field and frequency will be the value.
Alternative Logic
Program : s = {}
fs = {}
n = int(input("Enter no. of schools-"))
for i in range(n):
nm = input("Enter school name-")
s[nm] = input("area -")
for sn in s:
if s[sn] not in fs:
fs[s[sn]] = 1
else:
fs[s[sn]] += 1
print(fs)
Traversing a dictionary Object
Example: emp = {}
Create a dictionary Emp having employee no, n = int(input("Enter number of employees"))
name, designation , salary. The salary is to be for i in range(n):
assigned on the basis of designation as follows: eno = int(input("Enter employee number"))
Designation Salary name = input("Enter name")
Manager 80000 desig = input("Enter designation")
Executive 60000 if desig ==‘Manager':
Other 30000
salary=80000
The employee no is to be taken as key field and
elif desig==‘Executive':
rest of the values to be taken as a list. Write a
salary=60000
menu driven program to do the following
operations: else:
a Count all employees with a particular user salary=30000
given designation emp[eno]=[name,desig,salary]
b Search and display a record based on user
given employee no. # Example :{101:[‘devang’,’Manager’,80000]}
Traversing dictionary Object
while True:
ch=int(input("1:Count for user given designation\n2:Search on employee no\nEnter choice:"))
if ch==1:
cnt=0
ds=input("Enter designation")
for en in emp:
if emp[en][1]== ds:
cnt+=1
print("Count of employees for a designation:”,ds,"is",cnt)
elif ch==2:
empn=int(input(“Enter employee no”))
if empn in emp:
print(“employee no ,name ,designation“,empn,emp[empn][0],empn[empn][1])
else:
print("Record not found")
ans=input("Do you want to continue y/Y:")
if ans in "nN":
break
Traversing a dictionary Object
Example : prod = {}
Create a dictionary Product having product no , n = int(input("Enter number of products"))
name, category , quantity , cost, amount and for i in range(n):
package cost. The amount is to be calculated as plist = []
cost * quantity. The package cost is to be pno = input("Enter product number")
calculated on the basis of category as follows: nam=input(‘name’)
Category Package cost cat=input(‘cat’)
Cosmetic 8% of cost
qty=int(input(‘quantity’))
Electronic 6% of cost
cost=int(input(‘cost’))
Grocery 5% of cost
amt=qty*cost
Other 300
The product no is to be taken as key field and rest if cat==‘cosmetic’:
of the values to be taken as a list. Write a menu pcost=0.08*cost
driven program to do the following operations: elif cat==‘Electronic’:
a Count all products with a particular user given pcost=0.06*cost
category elif cat==‘Grocery’:
b Display the product no, name, amount whose pcost=0.05*cost
amount is more than 10000 else:
c Display the average amount for a particular pcost=300
category. plist=[nam,cat,qty,cost,amt,pcost]
d Search and display a record based on user prod[pno]=plist
given item no.
Traversing a dictionary Object
Example : #alternative code for creation
Create a dictionary Product having product no , prod = {}
name, category , quantity , cost, amount and n = int(input("Enter number of products"))
package cost. The amount is to be calculated as for i in range(n):
cost * quantity. The package cost is to be plist = []
calculated on the basis of category as follows: pno = input("Enter product number")
Category Package cost plist += [input("Enter name")]
Cosmetic 8% of cost
plist += [input("Enter category")]
Electronic 6% of cost
plist += [int(input("Enter quantity"))]
Grocery 5% of cost
plist += [float(input("Enter cost"))]
Other 300
The product no is to be taken as key field and rest plist += [plist[2]*plist[3]]
of the values to be taken as a list. Write a menu prod[pno]=plist
driven program to do the following operations: if prod[pno][1]=='Cosmetic':
a Count all products with a particular user given prod[pno]+=[0.08*plist[3]]
category elif prod[pno][1]=='Electronic':
b Display the product no, name, amount whose prod[pno]+=[0.06*plist[3]]
amount is more than 10000 elif prod[pno][1]=='Grocery':
c Display the average amount for a particular prod[pno]+=[0.05*plist[3]]
category. else:
d Search and display a record based on user prod[pno]+=[300]
given product no.
Traversing dictionary Object
while True: elif ch==3:
ch=int(input("1:Count for user given\ ucat=input("Enter category")
category\n2:Display with amount>10000\ tot,cnt=0,0
\n3:Display average amount for a category\ for pn in prod:
\n4:Search on product no \nEnter choice:")) if prod[pn][1]==ucat :
if ch==1: tot+=prod[pn][4]
cnt=0 cnt+=1
ucat=input("Enter category") print("Average amount for the category"\
for pn in prod: ucat, “ = ",tot/cnt)
if prod[pn][1]== ucat:
cnt+=1 elif ch==4:
print("Count of products for a category:”,\ pid=input("Enter product number:")
ucat,"is",cnt) if pid in prod:
print(prod[pid])
elif ch==2: else:
for pn in prod: print("Record not found")
if prod[pn][4]>10000: ans=input("Do you want to continue y/Y:")
print("product no ,name ,amount :”\ if ans in "nN":
,pn,prod[pn][0],prod[pn][4]) break
Traversing a dictionary Object
Example : stud = {}
Write a menu driven program to create a n = int(input("Enter no. of students-"))
dictionary containing roll number as key. The for i in range(n):
dets=[] #Value declared as an empty list
value part is given as a list having name,marks
rno = int(input("Enter roll no-"))
of 5 subjects, total marks, percentage and
dets += [input("enter name-")]
grade. The grade is assigned as per the given tot=0
criteria. for m in range(5):
Percentage Grade mk= float(input("marks-"))
>90 A dets +=[mk]
<90 and >=75 B tot+=mk
<75 C perc=tot/5
dets+=[tot,perc]
stud[rno]=dets
The program should have the following options
if stud[rno][7]>=90:
as menu
stud[rno] += ["A"]
 Count and display no. of Students of a elif stud[rno][7]>= 75:
given grade stud[rno] += ["B"]
 Display Minimum and maximum Percentage else:
 Display class average stud[rno] += ["C"]
 Display report Card for a given Roll no
Traversing a dictionary Object
Example : stud = {} #alternative code for creation
Write a menu driven program to create a n = int(input("Enter no. of students-"))
dictionary containing roll number as key. The for i in range(n):
dets=[] #Value declared as an empty list
value part is given as a list having name,marks
rno = int(input("Enter roll no-"))
of 5 subjects, total marks, percentage and
dets += [input("enter name-")]
grade. The grade is assigned as per the given tot=0
criteria. for m in range(5):
Percentage Grade mk= float(input("marks-"))
>90 A dets +=[mk]
<90 and >=75 B tot+=mk
<75 C perc=tot/5
dets+=[tot,perc]
if dets[7]>=90:
The program should have the following options
dets+= ["A"]
as menu
elif dets[7] >= 75:
 Count and display no. of Students of a dets+= ["B"]
given grade else:
 Display Minimum and maximum Percentage dets += ["C"]
 Display class average stud[rno]=dets
 Display report Card for a given Roll no
Traversing dictionary Object
while True: elif ch==3:
ch =cint(input("1-count of Students above\ gtot=0
a given grade\n2. Display Minimum and \ for rno in stud:
gtot +=stud[rno][6] #[6] is index of total
maximum Percentage\n3. Display class\ print("Class Average -",gtot/n)
average\n4.Report Card for a given \ elif ch==4:
Roll no \n Enter choice -")) r=int(input("Enter roll no -"))
if ch==1: for rno in stud:
gd,ctr = input("grade to search-")),0 if rno == r:
dets = stud[rno] #value assigned to a list
for rno in stud:
print("Report card")
if stud[rno][8] ==gd : print("rno -",rno,"\nnName -",dets[0])
ctr+=1 print("Marks of 5 subjects-\t")
print("students of grade",gd," = ",ctr) s=1
elif ch==2: for i in range(1,6):
max, min=0,100 print("Marks ",s," - ",dets[i])
s+=1
for rno in stud: print("Total - ", dets[6],"\t%age- ",dets[7])
if stud[rno][7]> max: break
max=stud[rno][7] else:
if stud[rno][7]< min: print("No such record")
min=stud[rno][7] ans = input("want to continue(Y/N")
print("Max & min %age -",max,min) if ans in “nN”:
break
Traversing a dictionary Object
Example : Create a dictionary Product having product no , name, quantity
, price, and amount. The amount is to be calculated as
price * quantity. Transfer the product name and price of those
products whose amount is greater than 10000 to a nested list
Program : prod = {}
n = int(input("Enter number of products"))
for i in range(n):
pno = input("Enter product number")
pnm = input("Enter name")
price = float(input("Enter price"))
qty = int(input("Quantity - "))
amt = price * qty
prod[pno] = [pnm,price,qty,amt]
plist=[]
for pno in prod:
if prod[pno][3] > 10000:
plist+=[[prod[pno][0],prod[pno][2]]]
print("The Product Dictionary ",prod)
print("The list of products with amount >10000",plist)
Traversing a dictionary Object
Example : Create a nested list to store book details. Each element of nested list is a
list object storing bookno, name ,quantity and price. Transfer only those
elements whose price is more than 1000 to another dictionary keeping
bookno as the key and bookname , quantity and price as value part. Display
the contents of the dictionary.
Program : bookdet=[]
n = int(input("Enter number of books"))
for i in range(n):
book=[]
bno,name = int(input("Enter book number :")), input("Enter name:")
qty , price =int(input("Enter quantity:")), float(input(" Enter price:"))
book=[bno,name,qty,price]
bookdet += [book]
print(bookdet)
bookdt={}
for rec in bookdet:
if rec[3]>1000:
bookdt[rec[0]]=[rec[1],rec[2],rec[3]]
print("dictionary elements:")
print(bookdt)
Nested Dictionary
When the value part of of a dictionary is a dictionary object itself, it is
called nested Dictionary.
The key of a nested dictionary can not be a dictionary object as
dictionary is a mutable data type.
Syntax : dictionary_object = {key:{key:value}, key:{key:value}..}
To refer to the value part of a nested dictionary object, the key of the
outer object and the key of the nested objects are given in [].
Syntax : dictionary_object[key1][key2]
Here key1 is the key field of outer dictionary and key2 is the key of nested
dictionary.
Example : >>> stud = {1: {'John': 97},2: { 'Marie': 79}}
>>> stud[1]
{'John': 97}
>>> stud[1]["John"]
97
In the above statement, 1 is the key of outer and John is the key of nested
Manipulation of Nested Dictionary
Program :
Example : stud = {}
Write a program to accept student’s n = int(input("no. of students-"))
name and marks for 5 subjects of n for i in range(n):
number of students. nm = input("enter student's name-")
Each element is stored in the form of a sub = {}
nested dictionary where the student for marks in range(5):
name is the key of the outer key and sn = input("sub name-")
subject name is the inner key and marks m = int(input("marks-"))
is the value part sub[sn] = m
Example –{ ‘ram’:{‘Eng’:90, ‘Maths’:99, stud[nm] = sub
‘Physics’:90, ‘Chemistry’:99, ‘Computer ctr=0
Science’:99}} ssub = input(“Enter sub name to Search-")
The program should count and display for stn in stud:
for sb in stud[stn]:
name, no. of students who have scored
if sb == ssub and stud[stn][sb]>80:
above 80% in a user given subject,
ctr+=1
print(stn," has scored",stud[stn][sb]," in",ssub)
print("no of students scored above 80% in",ssub, " =" ,ctr)
Assessment
Which statement is not valid for Dictionary?
a. It is a Mutable data type
b. The elements are stored as key:value pair.
c. When printed the dictionary elements are displayed as they
are added in the dictionary.
d. The key part of a dictionary can be a list or tuple.
Answer : d
Which statement(s) is/are invalid Dictionary declaration? Justify.
a. Dict = {1,2,3:”aa”}
b. Dict = {(1,2,3):”aa”}
c. Dict ={[1,2,3]:"aa"}
d. Dict ={"1", "2", "3":"aa"}
Answer : a. Invalid - multiple keys with one value
b. Valid
c. Invalid – List is mutable. Hence can’t be used as
key
d. Invalid - multiple keys with one value
Assessment
What is the output of following code?
d={ }
a, b, c = 1, 2, 3
d[a, b, c] = a + b − c
a, b, c = 2, 10, 4
d[a, b, c] = a + b − c
print(d)

(a) ((1, 2, 3) : 0, (2, 10, 4) : 8)


(b) [(1, 2, 3) : 0, (2, 10, 4) : 8)]
(c) {(1, 2, 3) : 0, (2, 10, 4) : 8}
(d) Error

Answer : C
Assessment
What will be the output of the following Python code?
d = {“a”:1,”b”:2,”c”:3,”d”:5}
str1 = “”
for k in d:
str1 += str(d[k])*2 + “ “
print(str1[::-1])
Answer : 55 33 22 11
Which operator cannot be used with Dictionary object
a. in
b. *
c. ==
d. !=
Answer : b

_______ operator can be used to access the key field of a dictionary


object.
Answer : in
Assessment
Choose the correct statement
a. A dictionary can have two same keys with different values.
b. A dictionary can have same values with different keys
c. A dictionary can have two same key:value pair
d. A dictionary can have neither same keys nor same values
Answer : b

Give one difference and one similarity between list and Dictionary.
Answer : Similarity – Both are Mutable
Difference - List is sequence datatype
Dictionary is a mapping data type.

The dictionary operation that takes a key and finds the corresponding
value, is known as ________
Answer : Lookup
Assessment
Give the output of the following: Give the output of the following:
dic1={} D1 = {“age”:20, “name”:”abc”, “salary”: 2000)
dic1[(1,2)] = 10 for k in D1 :
dic1[(1,2,3)] = 12 val = D1[k]
dic1[(1,2,4)] = 20 if val in D1:
sum =0 print(val, “is a member”)
for k in dic1 : else:
sum += dic1[k] print(val, “is not a member”)
print(len(dic1), sum) Output
Output 3 42 20 is not a member
abc is not a member
2000 is not a member
Assessment
What will be the output of
above Python code?
d1={"abc":5,"def":6,"ghi":7}
print(d1[0])
A. abc
B. 5
C. {"abc":5}
D. Error
Ans : D Which of the following is not a
declaration of the dictionary?
a. {1: ‘A’, 2: ‘B’}
b. dict([[1,”A”],[2,”B”]])
c. {1,”A”,2”B”}
d. { }
Ans c
Assessment
What type of error is returned by
the following code :
a={'a':"Apple", 'b':"Banana", 'c':"Cat"}
print(a[1]) Which statement is correct in reference to
a. KeyError the following
b. KeyNotFoundError A = {1 : "One", 2 : "Two", 4: "IV“, 3 : "Three"}
c. NotFoundError A[4] = "Four“
a. It will add value at the end of dictionary.
d. Syntax Error
b. It will modify value as the key already
Ans a exist.
c. It will add value in between of the
dictionary.
d. All of the above
Ans b
Dictionary Functions and Methods
len() - This function returns the number of elements (key-value pairs) in the dictionary.
Syntax : len(dictionary_name)
Example : >>>d1={1:”Ram”,2:”Laxman”,3:”sita”}
>>>len(d1)
3
clear() - This removes all elements from the dictionary. When clear() is used for a dictionary
object, it becomes an empty object.
Syntax : dictionary_name.clear()
Example: >>>d1.clear()
>>>print(d1)
{}
copy() - copy() method creates a copy of the dictionary object
Syntax : copied_object = original_object .copy()
Example : >>> d1 = {1:200,2:300,3:400,4:500,5:None}
>>> d2 = d1.copy()
>>> d2
{1: 200, 2: 300, 3: 400, 4: 500, 5: None}
>>> d1[4]=700
>>> d1
{1: 200, 2: 300, 3: 400, 4: 700, 5: None}
>>> d2
{1: 200, 2: 300, 3: 400, 4: 500, 5: None}
Dictionary Functions and Methods
items()
The method items() returns the dictionary items in the key-value pair form.
Syntax : dictionary_name.items()
Example: >>>d1={1:”number”,(2,3):”tuple”,”two”:”string”}
>>> d2.items()
dict_items([(1, 'number'), ((2, 3), 'tuple'), ('two', 'string')])
keys()
keys()method returns all the keys of the dictionary.
Syntax : dictionary_name.keys()
Example : >>> d1.keys()
dict_keys([1, (2, 3), ‘two'])
values()
values() method returns all the values of the dictionary
Syntax : dictionary_name.values()
Example : >>> d1.values()
dict_values(['number', 'tuple', 'string'])
get()
This function returns a value for the given key. If key is not present in the dictionary,
then get() method will not give any output
Syntax: dictionary_name.get(key)
Example: >>>d1={1:”Ram”,2:”Laxman”,3:”sita”}
>>>d1.get(1)
‘Ram’
Dictionary Functions and Methods
update() :
update() method merges key:value pairs from new
dictionary into the original dictionary by adding or replacing
the values as needed.
If items are not present in the old dictionary, they are added
in that. If the key of the item is already present in the old
dictionary, their value is updated with the new value.
Syntax : old_dict_name.update(second dict_name)
Example : >>> S1 = {'Name':'Kriti', 'Age':12}
>>> S2 = {'Name':'Rohan','Class':8}
>>> S1.update(S2)
>>> S1
{'Name': 'Rohan', 'Age': 12, 'Class': 8}
Dictionary Functions and Methods
fromkeys() : fromkeys() create a new dictionary from a sequence containing all keys and a common value,
which will be assigned to all the keys.If it is not a sequence, it gives type error.
Syntax : dict.fromkeys(<key sequence>,value)
Key sequence are the keys for new dictionary, Value is common value assigned to all keys,(if
value is omitted, None is assigned), dict can be any dictionary object
Example : >>> ndict = dict.fromkeys([1,3,4],200)
>>> ndict
{1: 200, 3: 200, 4: 200}
>>> ndict2 = dict.fromkeys([2,3,4])
>>> ndict2
{2: None, 3: None, 4: None}
>>> ndict3=dict.fromkeys([2,3,4],[1,2,3])
>>> ndict3
{2: [1, 2, 3], 3: [1, 2, 3], 4: [1, 2, 3]}
>>> d1= dict.fromkeys(("abc"),200)
>>> d1
{'a': 200, 'b': 200, 'c': 200}
Note :
To invoke fromkeys() method ,Instead of dict , an existing dictionary object can also be used. However
fromkeys() , will not change the value of the dictionary object through which it is invoked. The values
returned by fromkeys() can be displayed or assigned to another Dictionary object
Dictionary Functions and Methods
setdefault(): This method inserts a new key:value pair in the dictionary only if the
key does not exist and it will returns the current value of the element
inserted. If the key already exists, it returns the current value of the
key.
Syntax : dict.setdefault(<key>,value)
Key is the key to be added in the dictionary Value is value to be added
(if not given, the default None is assigned)
Example: >>> d1 = {1:200,2:300,3:400}
>> val1 = d1.setdefault(4,500)
>>> val1
500
>>> d1
{1: 200, 2: 300, 3: 400, 4: 500}
>>> val2 = d1.setdefault(4)
>>> val2
500
>>> val3 = d1.setdefault(5)
>>> val3
#No value
>>> d1
{1: 200, 2: 300, 3: 400, 4: 500, 5: None}
Dictionary Functions and Methods
pop(): pop() method takes the key of a dictionary as argument and deletes the item with
the matching key from the dictionary and displays the deleted value. If the key
given is not present in the dictionary, Python will result KeyError. However, a
customized message (instead of the default KeyError) can be given with pop()
method, which Python displays when the given key is not present in the dictionary
Syntax : dictionary_object.pop(key_value , customized message)
Example: >>> stud = {'Name':'Kriti','Age':12,'Class':8}
>>> stud.pop('Total Marks','Not found’)
'Not found‘
>>> stud.pop('‘Age”)
12
max(): The max() function returns maximum key value after comparing all elements of
the dictionary object. The keys must be of same data type otherwise it gives Type
Error
Syntax: max(dictionary_object)
Where dict is the dictionary from where maximum key is to be returned.
Example: >>> d1={1: 200, 2: 300, 3: 400, 4: 500}
>>> max(d1)
4
Dictionary Functions and Methods
min() This function returns minimum value after comparing keys
of all elements of the dictionary object. The keys must be
of same data type otherwise it gives TypeError.
Syntax: min(dictionary_object)
Example : >>> d1={1: 200, 2: 300, 3: 400, 4: 500}
>>> min(d1)
1
sum() This function returns sum of all the keys of the dictionary.
The keys must be of numeric type otherwise it results
TypeError
Syntax sum(dictionary_object)
Example >>> d1= {1: 200, 2: 300, 3: 400, 4: 500}
>>> sum(d1)
10
Dictionary Functions and Methods
popitem() - This method removes and returns the key:value pair which was entered
last in the dictionary.
Syntax : dictionary_object.popitem() Note :
Example : >>> d2 = {1:200,2:300,3:400,4:500,5:None} Popitem() method will result KeyError for
>>> d2.popitem() an empty dictionary object
(5, None)
>>> d2
{1: 200, 2: 300, 3: 400, 4: 500}
sorted() - This function returns a list which is sorted on the basis of keys of a
dictionary. However , the list can also have sorted values of the dictionary.
Syntax : sorted(dictionary_object)
Examples: >>> d2={1: 200, 2: 300, 3: 400, 4: 500}
d3 = sorted(d2,reverse=True)
>>> d3
Note :
[4, 3, 2, 1]
Sorted function will result TypeError
>>> dname={1:"Rohit",2:"Ajay",3:"Rajat"}
when the keys of the dictionary are not
>>> ds1 = sorted(dname.values())
of same type.
>>> ds1
['Ajay', 'Rajat', 'Rohit']
>>> ds2 = sorted(dname.items())
>>> ds2
[(1, 'Rohit'), (2, 'Ajay'), (3, 'Rajat')]
Dictionary Functions and Methods
del statement
del statement is used to remove an item in form of key:value pair from
a dictionary. If the key is not present, it will result an error .
When del is used with the dictionary object, Python will remove the
dictionary from the memory.
Syntax: del dictionary_name[key]
Example: >>> stud = {'Name':'Kriti','Age':12,'Class':8}
>>> del stud['Class']
>>> stud
{'Name': 'Kriti', 'Age': 12}
Example: >>> stud = {'Name':'Kriti','Age':12,'Class':8}
>>> del stud
>>> stud
NameError: name ‘stud' is not defined
Assessment
Rewrite the corrected code after correcting the errors. Also underline the errors.
D1 = dict{}
while i <= n:
a = input(“ enter name”)
b = input(“Enter address”)
D1(a) = b
L= D1.key()
for i in D1:
print(i, ‘\t’, D1[i])

Corrected code
D1= dict()
i=1
n = int(input(“Enter number of entries”))
while i <=n:
a = input(“Enter name”)
b = input(“Enter address”)
D1[a] = b
i = i+1
L = D1.keys()
for i in D1:
print(I,’\t’,D1[i])
Assessment
How is del dict_object different from del dict_object(key)?
del dict_object(key) is used to remove an item in form of
key:value pair from a dictionary by giving a key as parameter.
Example
>>> d1={1:"one",2:"two",3:"three"}
>>> del d1[2]
>>> d1
{1: 'one', 3: 'three’}
del dict_object is used to remove the entire dictionary
Example
del d1
>>> d1
NameError: name 'd1' is not defined
Assessment
How is clear() method different from del statement?
clear() removes all elements from the dictionary where as del is used to
remove an item in form of key:value pair from a dictionary.
clear() is a dictionary metod whereas del is a Python statement .
Example of clear()
>>> d1={1:”Ram”,2:”Laxman”,3:”sita”}
>>> d1.clear()
>>> print(d1)
{}
Example of del
del dictionary_name[key]
Example: >>> stud={'Name':'Kriti','Age':12,'Class':8}
>>> del stud['Class’]
>>> stud
{'Name': 'Kriti', 'Age': 12}
Assessment
How is pop() method different from popitem() method?
pop() method takes the key of a dictionary as argument and deletes the element
with the matching key and displays the deleted value.
popitem() removes and returns the key:value pair which was entered last in the
dictionary.
The pop() method takes the key as the argument where as in popitem() the
argument is not required.
Example of pop()
>>> d1={1:"one",2:"two",3:"three"}
>>> d1.pop(2)
'two'
>>> d1
{1: 'one', 3: 'three’}
Example of popitem()
>>> d1.popitem()
(3, 'three')
>>> d1
{1: 'one'}
Assessment
Which of the following can not be used to
remove an element from the dictionary?
a. del statement
b. pop()
c. popitem()
d. update
Ans : d
Which of the following will create a
dictionary with given keys and a common
value?
A. fromkeys()
B. update()
C. setdefault()
D. All of these
Ans : A
Assessment
Give the output of the following:
D1={ “c”:30, “B”:20, “a”: 40, “d”:10}
Give the output of the following:
st= “ “
d1= {5: “number”, “a” : “string”,(1,2):”tuple”} st2= 0
for x in d1.keys() : for i in D1:
if i not in st:
print( x, “:”, d1[x], end=’ ‘)
st += i
print(d1[x]*2) st2 += D1[i] //10
Output print(st)
print(st2)
5: number numbernumber l1 = list(D1.values())
a: string stringstring l1 .sort(reverse = True)
(1,2) : tuple tupletuple print( l1 )
Output
cBad
10
[40, 30, 20, 10]
Assessment
Give the output of the following:
List1 = [2 ,3, 4, 5, 6]
count = {}
Give the output of the following:
cnt = 0
a = {}
for num in List1:
a[1] = 1
count[num] = 0
a['1'] = a[1]*3
cnt +=1
a[1]= a[1]+1
count[num] = count[num] + cnt
count = 0
print(count)
for i in a:
for k in count.keys() :
count += a[i]
count[k] = k * count [k]
print(count)
print(count)
Output : Output : 5
{ 2 : 1, 3: 2, 4 : 3, 5 : 4, 6:5}
{2: 2, 3 : 6, 4: 12, 5 : 20, 6 : 30}
Assessment
What will the above Python code do?
dict = {"Phy":94,"Che":70,"Bio":82,"Eng":95}
dict.update({“Eco":72,"Bio":80})
A. dict will be overwritten as
dict = {“Eco":72,"Bio":80}
A. It will throw an error as dictionary cannot be
updated.
What will be the output of above
C. dict will be updated as
Python code?
{"Phy":94,"Che":70,"Bio":80,"Eng":95,"Eco":72}
a={1:’A’,2:’B’,3:’C’}
D. It will not throw any error but it will not do
b=a.copy()
any changes in dict
b[2]="D"
Ans : C print(a)
Ans : {1:’A’,2:’B’,3:’C’}
Assessment
Which of the following will delete key_value
pair for key = “tiger” in dictionary?
d1={“lion”:”wild”, “tiger”:”wild”,\
”cat”:”domestic”,”dog”:”domestic”}
A. del d1[“tiger”]
B. d1[“tiger”].delete()
C. delete(d1.[“tiger”]) Which of the following will give
D. del(d1.[“tiger”]) error if d1 is given as below?
Ans : A d1={‘d’:1,”b”:2,”c”:3}
A. print(d1.get(“e”))
B. d1[“a”] = 5
C. print(d1.len())
D. None of these
Ans : c
Assessment
Which of the following will bring same
change in the dictionary
D1={‘phase1’:1,’phase2’:2,’phase3’:3}
i. D1.pop(‘phase2’)
ii. del D1[‘phase2’]
iii. D1.update({‘phase1’:1 , ’phase3’:3}
a. i,ii
b. i,ii,iii
c. ii,iii Which function/method can be
d. i,iii used to result an empty dictionary?
Ans : a A. clear()
B. del
C. pop()
D. popitem()
Ans : A
Assessment
Give Output
D1 = {10:700,12:500,7:400}
D2 = dict(sorted(D1.items()))
print(D2)
D3 = D2.fromkeys(list(D2),sum(D2))
print(D3) Give Output
Ans : {7:400, 10: 700, 12:500} D1 = {“e01:”Ram”,”e02”:”Sita”}
{7: 29, 10: 29, 12: 29} print(D1.get(“e01”),D1.get(“Sita”))
Output :
Ram
Note:D1.get(“Sita”) will give no
output as the key “Sita” is not
present in the dictionary
Assessment
________ function/method is used to return each element of a dictionary
object.
Answer : items()

What will be the output


>>> d1 = {"Ram":"accts","sita":"system"}
>>> " accts” in d1
Answer : False
The items() method of dictionary returns ________.
a. List of tuples
b. Tuples of list
c. Tuples of tuples
d. Lists of list
Answer : a
Assessment
What will be the output
d1 = {“Akash”:2000,”Ram”:30000,”Ajay”:4000}
val1 = d1.setdefault(”Ajit”,5000)
val2 = d1.setdefault (”Ajit”,8000)
print(d1)
print(val1+val2)
Answer : {“Akash”:2000,”Ram”:30000,”Ajay”:4000, ”Ajit”,5000}
10000
What will be the output
d1 = {“Akash”:75,”Ram”:60,”Seeta”:45}
d2 = d1.copy()
d3 = d1
d1[“Ram”] = 90
print(d2)
print(d3)
Answer : {'Akash': 75, 'Ram': 60, 'Seeta': 45}
{'Akash': 75, 'Ram': 90, 'Seeta': 45}
Assessment
Which of the following can add an element to the dictionary?
(a) get()
(b) update()
(c) setdefault()
Answer : b

Which of the following method/function will not raise exception if the


key is not present in the dictionary?
(a) get()
(b) pop()
(c) del
(d) None of the above
Answer : a
Assessment
Which of the following will result a dictionary object as output?
(a) clear()
(b) del
(c) items()
(d) get()
Answer : a

Which of the following method/function will raise exception if the key


is not present in the dictionary?
(a) d1= dict.fromkeys([200])
(b) d1= dict.fromkeys((200,))
(c) d1= dict.fromkeys((200))
(d) d1= dict.fromkeys((200,200))
Answer : c
Assessment
Which of the following will remove the dictionary object from memory?
(a) clear()
(b) del
(c) popitem()
(d) pop()
Answer : b
What will be returned by the following:
get(), pop(), sorted(), clear(), setdefault(), popitem(), keys()
Answer : get() - only the value part
pop() - only the value part
sorted() – list
clear() - dictionary
setdefault() - only the value part
popitem() – tuple
keys() - list
Assessment
Name the function/method which does the following?
a. It returns the number of elements present in the dictionary
Ans : len()
b. It creates another dictionary object as a replica of an existing object.
Ans: copy()
c. This returns the value part of a key given as argument
Ans: get()
d. This creates a new dictionary with given keys and a common value
Ans : fromkeys()
e. It returns total of all key fields present in the dictionary
Ans : sum()
Assessment
Create a dictionary Employee having empno ,name,basic , hra,
da, pf, netsal, designation. The values of hra, da, pf,net is to be emp={}
calculated as follows: n=int(input("Enter number of employees"))
hra= 8% of basic for i in range(n):
da= 5% of basic elist=[]
pf= 10% of basic empno=int(input("Enter employee no”))
netsal= basic+ hra + da - pf name=input("Enter name")
The empno is to be taken as key field and rest of the values to basic=float(input("Enter basic salary"))
be taken in form of a list. Write a menu driven program to do the hra= 0.08*basic
following operations: da= 0.05*basic
a Calculate net salary pf= 0.10*basic
b Find max net salary
elist = [name , basic , hra , da ,pf]
c Count whose basic is more than 5000
emp[empno]=elist
d Assign designation as follows:
print(emp)
If net salary >= 50000, assign designation as Manager
If net salary < 50000 and >=10000, assign designation as
Executive
If net salary < 10000, assign designation as Clerk
e Count all employees with a user given designation
Assessment
while True:
ch=int(input("1:Calculate net salary\n2:Calculate maximum salary\n3:count basic>5000\
\n4:Assign designation\n5:Count with a user designation\nEnter choice"))
if ch==1:
for eno in emp:
emp[eno]+=[basic+ hra + da - pf]#Calculate net salary
print(emp)
elif ch==2:
max=0
for eno in emp:
if emp[eno][5]>max:
max=emp[eno][5]
print("Maximum net salary",max)
elif ch==3:
cnt=0
for eno in emp:
if emp[eno][1]>5000:
cnt+=1
print("Count of employees with basic more than 5000:",cnt)
Assessment
elif ch==4:
for eno in emp:
if emp[eno][5]>=50000:
emp[eno]+=['Manager']
elif emp[eno][5]<50000 and emp[eno][5]>=10000:
emp[eno]+=['Executive']
elif emp[eno][5]<10000:
emp[eno]+=['clerk']
print(emp)
elif ch==5:
cnt=0
des=input("Enter designation")
for eno in emp:
if emp[eno][6]==des:
cnt+=1
print("Count of employees with user designation",cnt)
ans=input("Want to continue y/Y")
if ans in "nN":
break
Project
Write a program to create a dictionary BOOK with the following elements where each element
has bookno as the key field and name, price, quantity, amount, category, discount as the value
part to be taken as a list. The amount is to be calculated as price and quantity. The discount is to
be calculated as follows:
Category Discount
Fic 15% of amount
Encyl 12% of amount
Acad 10% of amount
Other 500
Write a menu driven program to do the following operations:
a. Display all the records.
b. Search and display records on the basis of:
i Book no
ii Name
c. Display the maximum amount.
d. Display the average according to the following criteria:
i. Average of amount of all books
ii. Average of amount of user given category
Project
e. Edit the record on the basis of a user given book no
i. A user given book no
ii. A user given book name
f. Count the records on the basis of the following:
i. Count all records
ii. Count on the basis of a user given category
iii. Count on the basis of amount greater than user given amount.

You might also like