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'}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
