0% found this document useful (0 votes)
5 views

09-Python Dictionary-11-2024-2025

The document provides an overview of Python dictionaries, detailing their mutability, syntax, and various built-in functions such as len(), keys(), values(), and get(). It includes code examples demonstrating how to create, access, modify, and delete items in a dictionary. Additionally, it suggests practical programs for utilizing dictionaries, such as counting character occurrences and managing employee data.

Uploaded by

gaaliya08
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

09-Python Dictionary-11-2024-2025

The document provides an overview of Python dictionaries, detailing their mutability, syntax, and various built-in functions such as len(), keys(), values(), and get(). It includes code examples demonstrating how to create, access, modify, and delete items in a dictionary. Additionally, it suggests practical programs for utilizing dictionaries, such as counting character occurrences and managing employee data.

Uploaded by

gaaliya08
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Python - Dictionary

Computer Science 083


09

© Department of Computer Science, DPS R.K.Puram, New Delhi


Unit II: Computational Thinking and Programming – 1 2

● Dictionary: introduction, accessing items in a dictionary using keys, mutability


of a dictionary (adding a new term, modifying an existing item), traversing a

© Department of Computer Science, DPS R.K.Puram, New Delhi


dictionary, built-in functions/methods – len(), dict(), keys(), values(), items(),
get(), update(), del(), del, clear(), fromkeys(), copy(), pop(), popitem(),
setdefault(), max(), min(), sorted(); Suggested programs: count the number
of times a character appears in a given string using a dictionary, create a
dictionary with names of employees, their salary and access them.
Dictionary 3
DICTIONARY

Computer Science Department, D.P.S. R.K.Puram


MUTABLE
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
pairs of
MK MD DELHI PUBLIC SCHOOL R K PURAM COLLECTION
NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW

KEY bool int float str tuple

VALUE bool int float list tuple dict str set


Dictionary 4
CODE

Computer Science Department, D.P.S. R.K.Puram


M={"Rno":10,"Name":"Aryan"} # Creation of dict
print(type(M),M) # Displaying items
print(M["Rno"],M["Name"]) # Displaying values
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
M["Marks"]=95
PURAM NEW DELHI COMPUTER SCIENCE DEPT # MK
Adding an PUBLIC
MD DELHI item SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
print(type(M),M)
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
OUTPUT
<class 'dict'> {'Rno': 10, 'Name': 'Aryan'}
10 Aryan
<class 'dict'> {'Rno': 10, 'Name': 'Aryan', 'Marks': 95}
Dictionary 5
Dictionary (dict): It is mutable data type in Python, in which the values of

Computer Science Department, D.P.S. R.K.Puram


items can be changed. In other words, a dictionary is a collection which is
unordered, changeable and indexed. The content of dictionary (dict) is
enclosed inside a pair of curly braces { }.

DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
Syntax:
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER{<Index1/Key1>:<Value1>,<Index2/Key2>:<Value2>,...
SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER}SCIENCE DEPT
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
Examples of dict Contents:
#Dictionary
S={"Ino":101,"Item":"Pencil"}
M={1:200,2:160,3:180}
T={"Suraj":100,"John":150,"Ahmad":130}
Dictionary 6
CODE

Computer Science Department, D.P.S. R.K.Puram


M={"Rno":10,"Name":"Amar"}
print(M)
M["Rno"]+=2 # Changing the value of an item
DELHI PUBLIC SCHOOL R K PURAM NEW
M["Name"]="Amardeep" # DELHI COMPUTER
Changing the SCIENCE
valueDEPT
ofMKan
MD DELHI
itemPUBLIC SCHOOL R K
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER
print(M) SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
OUTPUT
{'Rno': 10, 'Name': 'Amar'}
{'Rno': 12, 'Name': 'Amardeep'}
Dictionary 7

CODE

Computer Science Department, D.P.S. R.K.Puram


M={1:16,4:10,3:15}
print(M,len(M))
for i in M:
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
print(i,M[i]) # Accessing Key and Values of items
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
M[i]*=1.1
COMPUTER # MD
SCIENCE DEPT MK Changing each
DELHI PUBLIC value
SCHOOL with
R K PURAM NEW10%
DELHImore
COMPUTER SCIENCE DEPT
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
print(M)
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
OUTPUT
{1: 16, 4: 10, 3: 15} 3
1 16
4 10
3 15
{1: 17.6, 4: 11.0, 3: 16.5}
dict() - To convert nested tuple to dictionary 8
CODE

Computer Science Department, D.P.S. R.K.Puram


T=(1,"Amar"),(2,"Geet"),(3,"Neel")
D=dict(T)
print(D)
OUTPUT
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
{1: 'Amar',
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD2:DELHI
'Geet', 3: 'Neel'}
PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
CODE
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW

T=((1,"Amar"),(2,"Geet"),(3,"Neel"))
D=dict(T)
print(D)
OUTPUT
{1: 'Amar', 2: 'Geet', 3: 'Neel'}
dict() - To convert nested list to dictionary 9
CODE

Computer Science Department, D.P.S. R.K.Puram


T=[(1,"Amar"),(2,"Geet"),(3,"Neel")]
D=dict(T)
print(D)
OUTPUT
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD
{1: 'Amar', 2:DELHI PUBLIC 3:
'Geet', SCHOOL R K PURAM NEW DELHI
'Neel'}
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
CODE
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW

T=[[1,"Amar"],[2,"Geet"],[3,"Neel"]]
D=dict(T)
print(D)
OUTPUT
{1: 'Amar', 2: 'Geet', 3: 'Neel'}
Dictionary - keys() and values() 10
CODE

Computer Science Department, D.P.S. R.K.Puram


M={"Rno":10,"Name":"Amar"}
print("Elements:",len(M)) # To find the number of items
print("K:",M.keys()) # To return list of keys
print("V:",M.values()) # To return list of values
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
print("D:",M)
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
for v SCIENCE
COMPUTER in M.values():
DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MK MDprint(v)
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
# To COMPUTEReach
display SCIENCE DEPT MK MD DELHI PUBLIC
value
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW

OUTPUT Elements: 2
K: dict_keys(['Rno', 'Name'])
V: dict_values([10, 'Amar'])
D: {'Rno': 10, 'Name': 'Amar'}
10
Amar
Dictionary - items() 11
CODE

Computer Science Department, D.P.S. R.K.Puram


D={"A":20,"B":15,"D":18} Dict.items()
L=D.items() Returns a
print(L) list of (key, value)
DELHI
forPUBLIC
k,vSCHOOL tuple
R K PURAM NEW DELHI COMPUTER
in D.items(): SCIENCEpairs
DEPTof
MKdictionary
MD DELHI PUBLIC SCHOOL R K
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
print(k,v,sep="#")
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
OUTPUT dict_items([('A', 20), ('B', 15), ('D', 18)])
A#20
B#15
D#18
Dictionary - get() 12
CODE

Computer Science Department, D.P.S. R.K.Puram


D = {"A":1, "B":2}
print(D.get("A","Not Found!")) Dict.get(<k>,<dv>)
print(D.get("D")) Returns a value associated with
print(D.get("B")) key. Returns
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE None
DEPT MK or Default
MD DELHI PUBLIC SCHOOL R K
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
Value (optional) if key not found
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MKprint(D.get("C","Not FoundNEW
MD DELHI PUBLIC SCHOOL R K PURAM !"))
DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW

OUTPUT
1
None
2
Not Found !
Dictionary - update() 13
CODE

Computer Science Department, D.P.S. R.K.Puram


Rec = {"Rno":1, "Name": "Amit"}
RU1 = {"Name": "Amit Sareen"}
# Updating the value of key "Name" Dict1.update(<Dict2>)
Rec.update(RU1) Updates value of the key (if
DELHI exists).
PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE
print(Rec) DEPTAdds a new
MK MD DELHIitem (ifSCHOOL
PUBLIC the R K
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI
RU2 = {"Fee":3500} keyPUBLIC
does not exist)
SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MK#MD Adding new SCHOOL
DELHI PUBLIC valueR with new
K PURAM NEWkey atCOMPUTER
DELHI the end SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
Rec.update(RU2)
print(Rec) OUTPUT
{'Rno': 1, 'Name': 'Amit Sareen'}
{'Rno': 1, 'Name': 'Amit Sareen', 'Fee': 3500}
Dictionary - updating without update() 14
CODE

Computer Science Department, D.P.S. R.K.Puram


Rec = {"Rno":1, "Name": "Amit"}
Rec["Name"]="Amit Sareen"
print(Rec)
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
Rec["Fee"]=3500
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MKprint(Rec)
MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
OUTPUT
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW

{'Rno': 1, 'Name': 'Amit Sareen'}


{'Rno': 1, 'Name': 'Amit Sareen', 'Fee': 3500}
Dictionary - del 15
CODE

Computer Science Department, D.P.S. R.K.Puram


Member = {'Mno':101,'Name':'Jaya','Type': 'Guest'}
print(Member)
del Member['Type'] del <Variable>
DELHI Deletes
PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE
print(Member) anMKitem
DEPT of dictionary
MD DELHI or R K
PUBLIC SCHOOL
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI complete dictionary
PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
del Member
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
print(Member)
SCHOOL OUTPUT
R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
{'Mno': 101, 'Name': 'Jaya', 'Type': 'Guest'}
{'Mno': 101, 'Name': 'Jaya'}
----------
NameError
Dictionary - clear() 16
CODE

Computer Science Department, D.P.S. R.K.Puram


L = {1:"One", 2:"Two"}
print('L:',L)
# clearing the content of dictionary
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
L.clear()
PURAM Dict.clear()
NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
Deletes theDELHI COMPUTER
content SCIENCE DEPT
of dictionary
print('L:',L)
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK (does
OUTPUT
notPUBLIC
MD DELHI delete the dictionary)
SCHOOL R K PURAM NEW

L: {1: 'One', 2: 'Two'}


L: {}
Dictionary - fromkeys() 17
CODE
Dict.fromkeys(<ck>,<v>)

Computer Science Department, D.P.S. R.K.Puram


K1 = [1, 2, 3];V1 = 100 Creates a dictionary from a
D1 = dict.fromkeys(K1, V1) collection of keys (tuple/list) with a
print(D1) default value for all if assigned, else
K2=('A','B','C');V2='Undefined' None is assigned to all the items
D2 = dict.fromkeys(K2, V2)
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
print(D2)
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MK K3=('100','200','300')
MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL
D3 =R Kdict.fromkeys(K3)
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
print(D3)
OUTPUT
{1: 100, 2: 100, 3: 100}
{'A': 'Undefined', 'B': 'Undefined', 'C': 'Undefined'}
{'100': None, '200': None, '300': None}
Dictionary - fromkeys() 18
CODE
Dict.fromkeys(<ck>,<v>)

Computer Science Department, D.P.S. R.K.Puram


K4 = [1, 2, 3];V4 = [100,200,300] Creates a dictionary from a
D4 = dict.fromkeys(K4,V4) collection of keys (tuple/list) with a
print(D4) default value for all if assigned, else
None is assigned to all the items
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW

OUTPUT
{1: [100, 200, 300], 2: [100, 200, 300], 3: [100, 200, 300]}
Dictionary - copy() 19
CODE

Computer Science Department, D.P.S. R.K.Puram


D1 = {'Name': 'John', 'DOB': '2002-02-12'};
print("D1 :",D1)
D2 = D1.copy()
Dict2=Dict1.copy()
Creates a copy of dictionary
DELHI PUBLIC SCHOOL
print("D2 R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
:",D2)
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
OUTPUT
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
D1 : {'Name': 'John', 'DOB': '2002-02-12'}
D2 : {'Name': 'John', 'DOB': '2002-02-12'}
Dictionary - Creating alias using assignment 20
CODE

Computer Science Department, D.P.S. R.K.Puram


D1 = {'Name': 'John', 'DOB': '2002-02-12'};
print("D1 :",D1)
Dict2=Dict1
D2 = D1 Creates an alias of dictionary
DELHI PUBLIC SCHOOL
print("D2 R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
:",D2)
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
D2['Name']='Jiya'
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
print("D1
SCHOOL R K PURAM:",D1)
NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW

OUTPUT
D1 : {'Name': 'John', 'DOB': '2002-02-12'}
D2 : {'Name': 'John', 'DOB': '2002-02-12'}
D1 : {'Name': 'Jiya', 'DOB': '2002-02-12'}
Dictionary - Creating alias & using shallow copy 21
CODE

Computer Science Department, D.P.S. R.K.Puram


P={12:"A",13:"B"}
Q=P
P[14]="C"
print(P,Q) R={}
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER
forSCIENCE
k,v inDEPT MK MD DELHI PUBLIC SCHOOL R K
P.items():
R=P.copy() # Shallow copy
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
P[15]="D"
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOLR[k]=v
R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MKprint(P,R)
MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW

OUTPUT
{12: 'A', 13: 'B', 14: 'C'} {12: 'A', 13: 'B', 14: 'C'}
{12: 'A', 13: 'B', 14: 'C', 15: 'D'} {12: 'A', 13: 'B', 14: 'C'}
Dictionary - pop() 22
CODE

Computer Science Department, D.P.S. R.K.Puram


Car={"No":1004,"Model":"Luxury","Fuel":"Petrol"}
print(Car)
Dict.pop(<Key>)
M=Car.pop("Model") Deletes and returns the
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE corresponding
print("Model:",M,end=" removed from ") DEPT MK MD DELHI PUBLIC SCHOOL
deleted value R K
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
print(Car)
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
OUTPUT
{'No': 1004, 'Model': 'Luxury', 'Fuel': 'Petrol'}
Model: Luxury removed from {'No': 1004, 'Fuel': 'Petrol'}
Dictionary - pop() 23
CODE

Computer Science Department, D.P.S. R.K.Puram


Car={"No":1004,"Model":"Luxury","Fuel":"Petrol"}
print(Car)
Dict.pop(<Key>)
M=Car.pop("Color") Deletes and returns the
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
PURAM NEWprint(M,end="
DELHI COMPUTER removed from
SCIENCE DEPT corresponding
") DELHI PUBLIC
MK MD SCHOOL Rdeleted
K PURAMvalue
NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
print(Car)
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
OUTPUT
{'No':1004, 'Model''Luxury', 'Fuel':'Petrol'}
-----------------
KeyError: 'Color'
Dictionary - popitem() 24
CODE

Computer Science Department, D.P.S. R.K.Puram


Car={"No":1004,"Model":"Luxury","Fuel":"Petrol"}
print(Car)
M=Car.popitem() Dict.popitem()
print(M,end=" removed from") Deletes
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE theMDlast
DEPT MK item
DELHI and SCHOOL R K
PUBLIC
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
returns the deleted item
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
print(Car)
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
OUTPUT
{'No': 1004, 'Model': 'Luxury', 'Fuel': 'Petrol'}
('Fuel', 'Petrol') removed from{'No': 1004, 'Model': 'Luxury'}
Dictionary - Add new item/modify existing 25
CODE

Computer Science Department, D.P.S. R.K.Puram


D={'Name':'Riya'} Update the value if matching Key found
print(D)
if 'Marks' in D:
DELHI D['Marks']+=10
PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
Add the item if matching Key not found
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
else: SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
COMPUTER
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
D['Marks']=10
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
print(D)
ALTERNATIVE 1
OUTPUT Using if..else
{'Name': 'Riya'}
{'Name': 'Riya', 'Marks': 10}
Dictionary - Add new item/modify existing 26
CODE

Computer Science Department, D.P.S. R.K.Puram


D={'Name':'Pankaj'} Update the value if matching Key found
print(D)
try:
DELHI D['Marks']+=10
PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
Add the item if matching Key not found
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
exceptSCIENCE
COMPUTER KeyError:
DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MK MD DELHI PUBLIC SCHOOL
D['Marks'] = 10 R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
print(D)
ALTERNATIVE 2
OUTPUT Using try..except
{'Name': 'Pankaj'}
{'Name': 'Pankaj', 'Marks': 10}
Dictionary - setdefault() 27
CODE

Computer Science Department, D.P.S. R.K.Puram


Returns Value from setdefault() and also modifies the content of the dict

<Value>=<Dict>.setdefault(<key>,<default_value>)
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
The NEW
PURAM setdefault() returns:SCIENCE DEPT MK MD DELHI
DELHI COMPUTER OPTIONAL
PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
● Value
SCHOOL of the
R K PURAM NEWkey if COMPUTER
DELHI it is in theSCIENCE
dictionary
DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW

● None if key is not in the dictionary and default_value is not specified

● default_value if key is not in the dictionary and default_value is specified


Dictionary - setdefault() 28
CODE

Computer Science Department, D.P.S. R.K.Puram


D = {'Name': 'Azar', 'Gender': 'Male'}
print(D)
DName =D.setdefault('Name',"Name not Available")
DELHI
DDOBPUBLIC=D.setdefault('DOB',"Date
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
not Available")
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
DGender=D.setdefault('Gender')
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC{'Name': 'Azar',
SCHOOL R K PURAM 'Gender':
NEW DELHI COMPUTER'Male'}
SCIENCE DEPT
MKDMobile=D.setdefault('Mobile')
MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI Azar
Name: COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R KOUTPUT
PURAM NEW
print("Name:",DName) DOB : Date not Available
print("DOB :",DDOB)
Gender: Male
Mobile: None
print("Gender:",DGender)
{'Name': 'Azar', 'Gender': 'Male',
print("Mobile:",DMobile) 'DOB': 'Date not Available',
print(D) 'Mobile': None}
Dictionary - setdefault() 29
CODE

Computer Science Department, D.P.S. R.K.Puram


D = {'Name': 'Azar', 'Gender': 'Male'}
print(D)
D_Name =D.setdefault('Name',"Name not Available")
D_DOB =D.setdefault('DOB',"NA")
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
D_Gender=D.setdefault('Gender')
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
print("Name:",D_Name)
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
print("DOB
SCHOOL :",D_DOB)
R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R KOUTPUT
PURAM NEW
print("Changed D:")
print(D)
{'Name': 'Azar', 'Gender': 'Male'}
Name: Azar
DOB : NA
Changed D:
{'Name': 'Azar', 'Gender': 'Male', 'DOB': 'NA'}
Dictionary - min() and max() 30
CODE

Computer Science Department, D.P.S. R.K.Puram


D={'P1':65,'P2':34,'P4':56,'P3':45}
print("Highest Key with its value:",max(D.items()))
print("Lowest Key with its value:",min(D.items()))
print("Highest Key:",max(D))
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
print("Lowest
PURAM Key:",min(D.keys()))
NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK
print("Highest MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
Value:",max(D.values()))
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
print("Lowest
SCHOOL Value:",min(D.values()))
R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW

OUTPUT Highest Key with its value: ('P4', 56)


Lowest Key with its value: ('P1', 65)
Highest Key: P4
Lowest Key: P1
Highest Value: 65
Lowest Value: 34
Dictionary - Finding frequency of values 31
CODE

Computer Science Department, D.P.S. R.K.Puram


D={'P1':60,'P2':30,'P3':50,'P4':60,'P5':30,'P6':10}
T=tuple(D.values())
print(T)
DF={}
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
MN=min(T)
MX=max(T)
COMPUTER
ALTERNATIVE 1
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MKprint(MN,MX)
MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER Traditional
SCIENCE DEPTMethod
MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
for I in range(MN,MX+1):
C=T.count(I) OUTPUT
if C>0: (60, 30, 50, 60, 30, 10)
DF[I]=C 10 60
print(DF) {10: 1, 30: 2, 50: 1, 60: 2}
Dictionary - Finding frequency of values 32
CODE

Computer Science Department, D.P.S. R.K.Puram


D={'P1':60,'P2':30,'P3':50,'P4':60,'P5':30,'P6':10}
DF={}
T=tuple(D.values())
for V in T:
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
if V not in DF:
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
COMPUTERC=T.count(V) ALTERNATIVE
SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW 2 DEPT
DELHI COMPUTER SCIENCE
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
DF[V]=C Python
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC Way
SCHOOL R K PURAM NEW
DF=dict(sorted(DF.items()))
print(DF)

OUTPUT
{10: 1, 30: 2, 50: 1, 60: 2}
Dictionary - sorted() 33
CODE

Computer Science Department, D.P.S. R.K.Puram


D={'P1':65,'P2':34,'P4':56,'P3':45}
L1=sorted(D)
print(L1);print(sorted(D.items()))
L2=dict(sorted(D.items()))
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
print(L2)
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
L3=sorted(D.values())
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MKprint(L3)
MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
OUTPUT
['P1', 'P2', 'P3', 'P4']
[('P1', 65), ('P2', 34), ('P3', 45), ('P4', 56)]
{'P1': 65, 'P2': 34, 'P3': 45, 'P4': 56}
[34, 45, 56, 65]
Dictionary functions 34

Computer Science Department, D.P.S. R.K.Puram


SNo. Function Description
1 len(Dict) Returns the total length of the Dictionary.
(number of items in the Dictionary)
2 max(<Collection>)
DELHI PUBLIC Returns maximum
SCHOOL R K PURAM NEW DELHI COMPUTER value
SCIENCE DEPT of the
MK MD collection
DELHI PUBLIC SCHOOL R K
PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI
3 min(<Collection>)
COMPUTER SCIENCE DEPT MK MD DELHI PUBLICReturns
SCHOOL minimum value
R K PURAM NEW of the
DELHI collection
COMPUTER SCIENCE DEPT
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
4 sorted(Dict,reverse= Returns a list in sorted order (ascending by
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
True) default)
5 type(variable) Returns the type of the passed variable. If
passed variable is dictionary, then it would
return a dict type.
Dictionary methods 35

Computer Science Department, D.P.S. R.K.Puram


SNo Methods Description
1 Dict.clear() Removes all elements of dictionary Dict
2 Dict.copy() Returns a copy of dictionary Dict
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K
PURAM3 NEWDict.fromkeys(<Keys>,
DELHI COMPUTER SCIENCE DEPTCreate
MK MD aDELHI
new PUBLIC
dictionary with
SCHOOL R keys fromNEW
K PURAM a DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC collection
<DefaultValue>) SCHOOL R K and
PURAM NEW DELHI
values from COMPUTER
a default SCIENCE
value. DEPT
MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCEAll values
DEPT MKare assigned
MD DELHI toSCHOOL
PUBLIC None ifR Default
K PURAM NEW
Value not mentioned.
4 Dict.get(key, For key, returns value or default if key not
default=None) in dictionary
Dictionary methods 36

Computer Science Department, D.P.S. R.K.Puram


SNo Methods Description
5 Dict.items()
Returns a list of (key, value) tuple pairs
6 Dict.keys()
Returns SCIENCE
DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER list of keys
DEPTof
MKdictionary
MD DELHI PUBLIC SCHOOL R K
PURAM7 NEWDict.setdefault(key,
DELHI COMPUTER SCIENCE DEPT Similar
MK MD to
DELHI PUBLIC
get(), but SCHOOL
will setR K PURAM NEW DELHI
COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT
MK MD DELHI PUBLIC SCHOOL R K PURAM NEWDict[key]=default
default=None) if key isDEPT
DELHI COMPUTER SCIENCE not MK
already in PUBLIC
MD DELHI
SCHOOL R K PURAM NEW DELHI COMPUTER SCIENCE DEPT MK MD DELHI PUBLIC SCHOOL R K PURAM NEW
dict
8 Dict1.update(Dict2) Adds dictionary key-values pair of Dict2 in
to Dict1
9 Dict.values()
Returns list of values of dictionary Dict
37

© Department of Computer Science, DPS R.K.Puram, New Delhi


Thank you!
Department of Computer Science
Delhi Public School R.K.Puram New Delhi

You might also like