Test Index

CBSE Class 12 Computer Science 2025 Paper Set 4 Get it on Google PlayDownload on the App Store

© examsnet.com
Question : 24 of 37
Marks: +1, -0
Consider the following dictionaries, D and D1 :
D={"Suman": 40, "Raj":55, "Raman":60}
D1={"Aditi":30, "Amit":90,"Raj":20}
(Answer using built-in Python functions only)
(i) (a) Write a statement to display/return the value corresponding to the key "Raj" in the dictionary D.
OR
(b) Write a statement to display the length of the dictionary D1.
(ii) (a) Write a statement to append all the key-value pairs of the dictionary D to the dictionary D1.
OR
(b) Write a statement to delete the item with the given key "Amit" from the dictionary D1.
Solution:  
(i) (a)
print(D.get("Raj"))        # 55
get() returns the value of the given key (D["Raj"] also gives 55).
OR (i) (b)
print(len(D1))             # 3
len() gives the number of key-value pairs in the dictionary; D1 has 3 items.
(ii) (a)
D1.update(D)
update() adds every key-value pair of D to D1. A key already present in D1 gets the new value from D, so "Raj" becomes 55:
{'Aditi': 30, 'Amit': 90, 'Raj': 55, 'Suman': 40, 'Raman': 60}
OR (ii) (b)
D1.pop("Amit")             # removes the item and returns 90
pop() deletes the item with the given key (del D1["Amit"] also works). D1 becomes {'Aditi': 30, 'Raj': 20}.
© examsnet.com
Advertisements
Go to Question: