Advertisements
Advertisements
Question
Assuming that D1 is a dictionary in Python.
Write a single statement using a BUILT_IN function to add the key:
value pair ‘RNo’: 12, if the key ‘RNo’ is not present in D1. However, if the key ‘RNo’ is present, the function should return its value.
Short Answer
Advertisements
Solution
D1.setdefault('RNo', 12)
The
setdefault() The method checks if the key ‘RNo’ exists in the dictionary.- If the key is not present, it inserts the key with the value
12. - If the key is already present, it does nothing to the dictionary and simply returns the existing value.
shaalaa.com
Is there an error in this question or solution?
2025-2026 (March) Set 4
