Q.Assuming that D1 is a dictionary in Python,
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Dictionary membership tests use the in operator on keys; dict.values() checks values. setdefault() adds a key-value pair only if absent (returning the value either way), while clear() empties the dictionary.
Python dictionaries are hash tables that map keys to values. The language provides elegant, built-in ways to test membership, conditionally insert, and manipulate these mappings without verbose if-else blocks.
Part (i): Membership Testing
(a) Check if key 'RNo' is present
The in operator tests membership in a dictionary's key space by default. It returns a boolean and runs in average constant (O(1)) time thanks to hashing.
'RNo' in D1
This expression evaluates to True if 'RNo' is a key in D1, False otherwise.
You can also write 'RNo' not in D1 to test absence. Never use D1.has_key('RNo') — that method was removed in Python 3.
(b) Check if any key has value 12
Values are not hashed, so we must search through them. The .values() method returns a view of all values; combine it with in:
12 in D1.values()
This scans the values linearly (worst-case O(n)) and returns True if at least one key maps to 12.
Writing 12 in D1 checks if 12 is a key, not a value. Always use .values() when searching by value.
Part (ii): Conditional Insertion and Deletion
(a) Add 'RNo': 12 if absent, else return existing value
Python's setdefault(key, default) method is purpose-built for this: it returns D1[key] if the key exists, otherwise inserts key with value default and returns default.
D1.setdefault('RNo', 12)
How it works:
- Checks if
'RNo'is inD1. - If present, returns the current value (no modification).
- If absent, sets
D1['RNo'] = 12and returns12.
This is cleaner than the equivalent:
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.