Python / Core Python Fundamentals Interview Questions
How do you use dictionary comprehension to transform data payloads in Python?
Dictionary comprehension is the clean, Pythonic way to build or transform a dict in one expression. The syntax mirrors list comprehension: {key_expr: value_expr for variable in iterable if condition}. It is commonly used when processing API response payloads, config maps, or any key-value data that needs normalisation or filtering.
# Invert a dictionary (swap keys and values) codes = {'USD': 1, 'EUR': 2, 'GBP': 3} inv = {v: k for k, v in codes.items()} # {1: 'USD', 2: 'EUR', 3: 'GBP'} # Filter an API response payload  keep only active users users = { 'alice': {'active': True, 'role': 'admin'}, 'bob': {'active': False, 'role': 'user'}, 'carol': {'active': True, 'role': 'user'}, } active_users = {name: data for name, data in users.items() if data['active']} # {'alice': {...}, 'carol': {...}} # Normalise keys from camelCase API payload to snake_case import re payload = {'firstName': 'Alice', 'lastName': 'Smith', 'userId': 42} to_snake = lambda s: re.sub(r'(?!^)(?=[A-Z])', '_', s).lower() normalised = {to_snake(k): v for k, v in payload.items()} # {'first_name': 'Alice', 'last_name': 'Smith', 'user_id': 42}
Nesting a comprehension inside another is possible but quickly becomes hard to read. If the transformation logic exceeds one or two conditions, break it into a helper function and call it from the comprehension. Dict comprehension also pairs naturally with zip() when you have two parallel sequences of keys and values:
headers = ['name', 'age', 'city'] values = ['Alice', 30, 'NYC'] record = {k: v for k, v in zip(headers, values)} # {'name': 'Alice', 'age': 30, 'city': 'NYC'}
More Related questions...