A data analyst is processing a large dataset of customer transactions. The dataset is stored as a list of dictionaries, each with keys 'amount' and 'date'. The analyst needs to compute the total revenue for 2024. They write: total = 0 for t in transactions: if t['date'].year == 2024: total += t['amount'] They then run it and get a KeyError: 'date'. After inspection, they notice that some records have a 'Date' key (capital D) instead. The analyst wants to fix this without modifying the data. Which approach will correctly sum amounts regardless of key case?
Correct: get with fallback handles both key casings.
Why this answer
Option A is correct because `dict.get(key, default)` safely attempts to retrieve the value for 'date', and if that key is missing, it falls back to retrieving the value for 'Date'. This handles the case inconsistency without modifying the original data and avoids a KeyError. The `.year` attribute is then accessed on the returned date object.
Exam trap
Python Institute often tests the distinction between direct key access (`dict[key]`) which raises KeyError, and the safer `dict.get()` method, and the trap here is that candidates may think a try-except block is the only way to handle missing keys, overlooking the more Pythonic and concise `.get()` with a fallback.
How to eliminate wrong answers
Option B is wrong because a try-except block would work but is less Pythonic and less efficient than using `.get()` with a fallback; it also requires an extra nested block and is not the simplest fix. Option C is wrong because converting all keys to lowercase would require modifying the data (e.g., creating new dictionaries), which violates the requirement 'without modifying the data'. Option D is wrong because a list comprehension with conditional chaining does not directly solve the key-case issue; it would still need a way to handle the missing key, and chaining conditions like `if t.get('date', t.get('Date')).year == 2024` is essentially the same as option A but in a comprehension, not a fundamentally different approach.