Dictionary 2024 2025
Dictionary 2024 2025
Dictionary
Definition:
It is an unordered collection of
items where each item consist of a key
and a value.
1.Dictionary Operation
2.Traversing in a Dictionary
1.Dictionary Operation
Dictionary Operation
There is only one operator available in Python Dictionary
that is Membership Operator.
The membership operator checks if the key is present in the
dictionary or not if present it returns True, else it returns
False.
>>> dict1 = {'Mohan':95,'Ram':89,'Sai':92, 'Sangeeta':85}
>>> ‘Sai' in dict1
True
The not in operator returns True if the key is not present in
the dictionary, else it returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Sai':92, 'Sangeeta':85}
>>> 'Sai' not in dict1
False
2.Traversing in a Dictionary
Traversing a Dictionary
We can access each item of the dictionary or
traverse a dictionary using for loop.
Given Dictionary:
dict1={'Mohan':90,'Glen':89,'Sri Ram':92, 'Sangeetha':85}
Method 1
for i in dict1:
print(i,':',dict1[i])
output
Mohan : 90
Glen : 89
Sri Ram : 92
Sangeetha : 85
Method 2 :
dict1={'Mohan':90,'Glen':89,'Sri Ram':92, 'Sangeetha':85}
for k, v in dict1.items():
print(k,':’,v)
Output
Mohan : 90
Glen : 89
Sri Ram : 92
Sangeetha : 85
CLASSROOM ACTIVITY
Sample Input
66555454:”Gouri",45654633:”shaji",45645645:”M
anav",56456456:"Juan“,55445655:"Glen"}
CODING
Phone_dict={66555454:”Gouri",4565463:”shaji",4564564
5:”Manav",56456456:"Juan“,45655:"Glen"}
for i in Phone_dict:
print(i,':',Phone_dict[i])
FLIP LEARNING TASK
CODING BY DYNAMIC INPUT
How many Friend's Phone number to be Stored :3
Enter the Phone Number of your friend:33335343
Enter the Name of your friend:Gouri
Enter the Phone Number of your friend:35343433
Enter the Name of your friend:Glen
Enter the Phone Number of your friend:33336666
Enter the Name of your friend:Abinav
MY Friend Phone Details
33335343 : Gouri
35343433 : Glen
33336666 : Abinav
CODING BY DYNAMIC INPUT
EMPLOYEE_NAME SALARY
edward 600
sai 800
Andrew 400
LAB PRACTICAL
for K in S:
Sum=0
for i in range(3):
Sum+=S[K][i]
if Sum/3>=90:
Grade="A"
elif Sum/3>=60:
Grade="B"
else:
Grade="C"
print(K,"–",Grade)
Built- in Functions & Methods in Dictionary
TODAY’S TOPIC
values(),
items(),
get(),
update(),
Built- Functions in Dictionary
Function & Description
>>> dict1.get('Name')
'Aman’
<dictionary>.get(key,[default value])
Example
Emp2={"Name":"Gouri","Salary": 3000,"Dep":"IT"}
print(Emp2.get("Age","Error!!!!The given Key is not
found"))
update()-
This method merges key : value pair from the new
dictionary into the original dictionary, adding or
replacing as needed. The items in the new
dictionary are added to the old one and override
any items already there with the same keys.
Example:
The given Dictionary:
Emp1 = {'Name': 'Glen', 'Salary': 2000, 'Age': 16}
Emp2 = {'Name': 'Gouri', 'Salary': 3000, 'Dep': 'IT’}
Emp1.update(Emp2)
Print(Emp1) print(Emp2)
After Updating Emp1 and Emp2:
Emp1 : {'Name': 'Gouri', 'Salary': 3000, 'Age': 16, 'Dep': 'IT'}
Emp2 : {'Name': 'Gouri', 'Salary': 3000, 'Dep': 'IT'}
CLASSROOM ACTIVITY
Create a dictionary of odd numbers between 1 and
10, where the key is the decimal number and the
value is the corresponding number in words.
Example:
ODD = {1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
Perform the following operations on this dictionary:
(a) Display the all the keys present in the dictionary
(b) Display the all the values present in the dictionary
(c) Display the items present in the dictionary
(d) Find the length of the dictionary
(e) Check if 7 is present or not
(f) Check if 2 is present or not
(g) Retrieve the value corresponding to the key 9
>>> ODD = {1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven', 9: 'Nine'}
(a) Display the keys
>>> ODD.keys()
dict_keys([1, 3, 5, 7, 9])
(b) Display the values
>>> ODD.values()
dict_values(['One', 'Three', 'Five', 'Seven', 'Nine'])
(c) Display the items
>>> ODD.items()
dict_items([(1, 'One'), (3, 'Three'), (5, 'Five'), (7, 'Seven'), (9,
'Nine')])
(d) Find the length of the dictionary
>>> len(ODD)
5
(e)Check if 7 is present or not
>>> 7 in ODD ----True
(f) Check if 2 is present or not
>>> 2 in ODD ----False
(g) Retrieve the value corresponding to the key 9
>>> ODD.get(9)-- 'Nine'
RECAP OF TODAY’S TOPIC
Home Work
del(), clear(),
fromkeys(), copy(),
pop(), popitem(),
setdefault(),
RECAP OF LAST CLASS
TOPIC
TODAY’S TOPIC
Built- in Functions & Methods Python in Dictionary
Continue
setdefault(),
del(), clear(), pop(),
fromkeys()
setdefault() method
Marks={1:350,2:400,3:450}
Marks.setdefault(4,350)
print(Marks)
Marks.setdefault(3,350)
print(Marks)
Marks.setdefault(6)
print(Marks)
{1: 350, 2: 400, 3: 450, 4: 350}
{1: 350, 2: 400, 3: 450, 4: 350}
{1: 350, 2: 400, 3: 450, 4: 350, 6: None}
Dictionary
Deleting Dictionary Items
del, pop() and clear() statement are used to remove
items from the dictionary.
del ()-used to remove key
popitem(), fromkeys(),copy()
popitem() – removes last item from dictionary
and return the removed dictionary item.
x={'name':'Aman','age':37,'country':'India'}
n=x.popitem()
print(n)
print(type(n))
print(x)
OUTPUT->
('country', 'India')
<class 'tuple'>
{'name': 'Aman', 'age': 37}
Note : popitem() takes no arguments
Built-in Methods in Dictionary
Method & Description
fromkeys()
1. It is used to create new dictionary from a sequence
containing all the keys and a common value, which
will be assigned to all the keys.
keys = {'a', 'e', 'i', 'o', 'u' }
value ="Vowel"
vowels=dict.fromkeys(keys,
value)
print(vowels)
OUTPUT->
{'i': 'Vowel', 'u': 'Vowel', 'e': 'Vowel', 'a': 'Vowel', 'o':
'Vowel'}
fromkeys()
2.If you only specify the key sequence and do not give any value , it
will take None as the values for the keys
>>>Newdict=dict.fromkey((3,4,5))
>>> print(Newdict)
{3: None, 4: None, 5: None}
>>> D1=dict.fromkeys((3,))
>>> D1
{3: None}
>>> D2=dict.fromkeys([3])
>>> D2
{3: None}
CLASSROOM ACTIVITY
x ={'Name':'Aman','age':37,'country':'India'}
print(x)
y=x.copy()
print(y)
print(id(x))
print(id(y))
y["Mobile"]=33333
print("After adding New item in Y")
print(x)
print(y)
print(id(x))
print(id(y))
OUTPUT
Example:
#1. Dictionary having homogeneous keys (all of tuple type)
d1={(1,2):"One",(3,4):"Two"}
print(d1)
Example:
d1={(1,2):"One",(3,4):"Two"}
d2={"Name":"Sekar","Address":"Manama"}
d3={40:"Fourty", 50:"Fifty"}
d4={1.2:"A", 3.4:"B"}
print(min(d1),min(d2),min(d3),min(d4))
print(max(d1),max(d2),max(d3),max(d4))
Output
min and Max
(1, 2) ,Address, 40, 1.2
(3, 4) ,Name ,50, 3.4
sum()
Example:
d1={(1,2):"One",(3,4):"Two"}
d2={"Name":"Sekar","Address":"Manama"}
d3={40:"Fourty", 50:"Fifty"}
d4={1.2:"A", 3.4:"B"}
Out of the above given dictionary only two dictionaries d3 and d4 have the keys
which ca be added(int and float type)
The keys of dictionaries d1 and d2 are not addition compatible as the tuple and
string can not be added.
print(sum(d3))
print(sum(d4))
print(sum(d1))
print(sum(d2))
Output:
90
4.6
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Note:
max(),min(),and sum() will only work with:
sorted()
sorted() function
The sorted() function will return the sorted result always in the list
form.
.
Syntax:
sorted(<dict>,[reverse=False])
D1={1002:"Johan",1001:"Gouri",1004:"Ram",1003:"Annu"}
#Sorting By Default
print(D1)
D2=sorted(D1)
print(D2)
[1001, 1002, 1003, 1004]
D1={(3,4):"Two",(1,2):"One"}
D2=sorted(D1)
print(D2)
[(1, 2), (3, 4)]
D3={"Johan":"Manama","Gouri":"Riffa","Ram":"Sanad","Annu":"Manama"}
D4=sorted(D3)
print(D4)
['Annu', 'Gouri', 'Johan', 'Ram']
D8={1002:"Johan",1001:"Gouri",1004:"Ram","1003":"Annu"}
D9=sorted(D8)
print(D9)
TypeError: '<' not supported between instances of 'str' and 'int'
len(), dict(), keys(), values(), items(), get(), update(),
del(), clear(), fromkeys(), copy(), pop(), popitem(),
setdefault(), max(), min(), count(), sorted(), copy();
CLASSROOM
44.Write a program ACTIVITY
to input your friends’ names and their
Phone Numbers and store them in the dictionary as the key-
value pair. Perform the following operations on the
dictionary:
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
Home Work