9 Notes Dictionary
9 Notes Dictionary
Key Value
"ELENA JOSE" 450
Marks "PARAS GUPTA" 467
"JOEFFIN JOSEPH" 480
Here,
- Key PARAS GUPTA with a value 467
- Key ELENA JOSE with a value 450
- Key JOEFFIN JOSEPH with a value 480
Creating Dictionary
EXAMPLE 1:
For example, let us create and print the Marks dictionary:
>>> Marks = {"ELENA JOSE" : 450, "PARAS GUPTA" : 467, "JOEFFIN JOSEPH" : 480}
Here ELENA JOSE is the key and its value is 450, PARAS GUPTA is the key and its value is 467.
EXAMPLE 2:
EXAMPLE 3:
Similarly, let us create another dictionary called Student with following key : value pairs:
>>> Student = { "Name" : "Surbhi Gupta",
"Rollno" : 11,
"Address" : "F444 - MIG Flat, Sec-7, Rohini",
"Phone" : "7286798500"
}
>>> print (Student)
{'Name': 'Surbhi Gupta' , 'Rollno': 11 , 'Address': 'F2/27 - MIG Flat, Sec-7, Rohini' , 'Phone':
'7286798500'}
Example 4 : You make a dictionary of your friends names and phone numbers.
Friends name will be a key, phone number will be a value.
print(teachers[“HARMEET”])
Will print Physics
for i in teachers:
print(i, teachers[i])
Output:
BHAWNA Math
HARMEET Physics
MEENAL Chemistry
for i in Marks:
print(i, Marks[i])
Output:
ELENA JOSE : 450
PARAS GUPTA: 467,
JOEFFIN JOSEPH : 480
Using keys() and values() function
• keys() function displays only the keys of the dictionary
• values() function displays only the values of the dictionary
Output:
dict_keys(['BHAWNA', 'HARMEET', 'MEENAL'])
dict_values(['Math', 'Physics', 'Chemistry'])
teachers={"BHAWNA":"Math", "BHAWNA":"Phy",
"MEENAL":"Chemistry"}
# This is erroneous because Key BHAWNA is NOT unique.
print(teachers)
# It will consider only this as dictionary :
{'BHAWNA': 'Phy', 'MEENAL': 'Chemistry'}
6) Values can be same. Example two teachers can have the same value :
Math
Example : BHAWNA and HARMEET both values Math here:
• So we have noted that as Dictionaries are Mutable, Value can be changed for a pair.
del(teachers["MEENAL"])
print(teachers)
(Meenal:Chemistry pair is deleted
Output:
{'BHAWNA': 'Math', 'HARMEET': 'Physics'}
Note : As we write del and then (, same way we write len function :
print(len(teachers))
(ii) A dictionary with 3 student names as keys and their aggregate marks
percentages as respective values.
Ans : {'Amar’:80, 'Akbar':78.5, 'Anthony':80.6}
.
(i) True (ii) False (iii) (iv) False
False
(v) (vi) True
False
Ans:
Programs
Write a program to accept a key from the user and remove that key from the dictionary if
present.
Solution :
d1 = {1 : 25, 2 : 90, 3 : 50}
k=int(input(“Enter any key”))
if k in d1:
d1.pop(k)
print(d1)# dictionary will be displayed without the value that is deleted
else:
print(“Key not found”)
Solution:
d1={1:”Aman”,2:”Suman”,3:”Aman”,4:”Kranti”,5:”Suman”}
print(len(d1))
Q3. Accept a key from the user and modify it’s value.
Solution:
d1={1:”Aman”,2:”Suman”,3:”Aman”,4:”Kranti”,5:”Suman”}
d1[k]=v
print(d1)