Skip to content
Question 43 of 97

Q.Assuming that D1 is a dictionary in Python,

(i)
(a) Write a Python expression to check if the key, 'RNo' is present in D1. OR
(b) Write a Python expression to check if any key in D1 has a value 12.
(ii)
(a) 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. OR
(b) Write a single statement to delete all the elements from D1.
CBSECBSE Class XII Board 2026Subjective· 2mImportance★★★★★
44% · 43/97 Questions
🔒 Locked · start free trial →

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.

Tip

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.

Watch out

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:

  1. Checks if 'RNo' is in D1.
  2. If present, returns the current value (no modification).
  3. If absent, sets D1['RNo'] = 12 and returns 12.

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.