Question
Python Dictionary Comprehensions: Create Dictionaries from Key-Value Pairs
Question
Can Python list-comprehension-style syntax be used to create a dictionary by iterating over matching keys and values?
For example, given keys and values, how can I create a dictionary from their paired items?
# Intended result: a dictionary mapping each key to its value
d = {... for k, v in zip(keys, values)}
Short Answer
Python has dictionary comprehensions, which build a dictionary in one expression. Use curly braces and write a key: value pair before the for clause:
d = {k: v for k, v in zip(keys, values)}
You will learn the syntax, how zip() pairs two sequences, how duplicate keys behave, and when a comprehension is preferable to a regular loop.
Concept
A dictionary comprehension is a compact way to create a new Python dictionary from an iterable such as a list, range, string, or another dictionary.
Its general form is:
{key_expression: value_expression for item in iterable}
Unlike a list comprehension, which produces one value for each iteration, a dictionary comprehension must produce two parts:
- a key before the colon (
:) - a value after the colon
For paired key and value sequences, zip(keys, values) produces pairs. A dictionary comprehension can unpack each pair into k and v and store k: v.
keys = ["name", "age", "city"]
values = ["Ava", 29, "Lisbon"]
person = {k: v for k, v in zip(keys, values)}
print(person)
# {'name': 'Ava', 'age': 29, 'city': 'Lisbon'}
This matters because dictionaries are central to Python programs: they represent JSON-like data, configuration settings, lookup tables, API data, counters, and records. Comprehensions make simple transformations concise while keeping the mapping relationship visible.
Mental Model
Think of zip(keys, values) as a machine that places one label beside one item:
"name" + "Ava"
"age" + 29
"city" + "Lisbon"
A dictionary comprehension is a worker at the end of that machine. For every pair, it files the item in a cabinet drawer labeled by the key:
key "name" → value "Ava"
The colon in k: v means: “put value v under label k.”
Syntax and Examples
The basic dictionary-comprehension syntax is:
new_dictionary = {
key_expression: value_expression
for item in iterable
}
For two matching sequences:
keys = ["red", "green", "blue"]
values = ["#ff0000", "#00ff00", "#0000ff"]
colors = {key: value for key, value in zip(keys, values)}
print(colors)
# {'red': '#ff0000', 'green': '#00ff00', 'blue': '#0000ff'}
zip(keys, values) yields these tuples:
("red", "#ff0000")
("green", "#00ff00")
("blue", "#0000ff")
The comprehension unpacks each tuple into key and value, then adds key: value to colors.
You can also transform either side:
Step by Step Execution
Consider this code:
keys = ["username", "active", "visits"]
values = ["sam", True, 14]
profile = {k: v for k, v in zip(keys, values)}
Step by step:
zip(keys, values)starts pairing corresponding positions from both lists.- Its first pair is
("username", "sam"). - The comprehension assigns
k = "username"andv = "sam". - It creates the dictionary entry
"username": "sam". - The next pair is
("active", True), producing"active": True. - The final pair is
("visits", 14), producing"visits": 14. profilebecomes:
{"username": "sam", "active": True, "visits": }
Real World Use Cases
Dictionary comprehensions are useful whenever you need to turn, clean, filter, or reshape data into key-value form.
- Build configuration dictionaries from setting names and supplied values.
- Turn CSV columns into records by pairing header names with row values.
- Create lookup tables, such as product ID → product name.
- Filter API fields before sending a request.
- Normalize imported data, such as converting field names to lowercase.
- Invert or transform mappings, such as user ID → display name.
Example: turn CSV-style headers and a row into a record:
headers = ["id", "email", "status"]
row = [101, "user@example.com", "active"]
record = {header: value for header, value in zip(headers, row)}
print(record)
# {'id': 101, 'email': 'user@example.com', 'status': 'active'}
Real Codebase Usage
In production code, dictionary comprehensions are commonly used for small, direct data transformations. A few common patterns are:
Filter optional values before an API request
form_data = {
"name": "Rina",
"email": "rina@example.com",
"phone": None,
}
payload = {key: value for key, value in form_data.items() if value is not None}
# {'name': 'Rina', 'email': 'rina@example.com'}
Convert keys or values into a consistent format
raw_settings = {"MAX_RETRIES": "3", "DEBUG": "true"}
settings = {key.lower(): value for key, value in raw_settings.items()}
Build a lookup dictionary
users = [
{"id": 10, "name": "Ana"},
{"id": 20, "name": "Bo"},
]
users_by_id = {user["id"]: user for user in users}
Common Mistakes
Forgetting the colon between key and value
This is not a dictionary comprehension:
# Broken: no key: value pair
result = {k, v for k, v in zip(keys, values)}
Use a colon:
result = {k: v for k, v in zip(keys, values)}
Accidentally creating a set
Curly braces do not always mean a dictionary. Without :, Python interprets the expression as a set comprehension.
pairs = {(k, v) for k, v in zip(keys, values)}
# This is a set of tuples, not a dictionary.
Expecting zip() to report unequal lengths
zip() stops at the shortest iterable:
keys = ["a", "b", "c"]
values = [1, 2]
result = {k: v for k, v in (keys, values)}
(result)
Comparisons
| Tool | Result | Best use |
|---|---|---|
| List comprehension | A list | Produce an ordered sequence of values. |
| Dictionary comprehension | A dictionary | Produce key → value mappings. |
| Set comprehension | A set | Produce unique values. |
dict(zip(keys, values)) | A dictionary | Directly pair two sequences with no transformation or filtering. |
Regular for loop | Any structure | Use when the logic needs several steps or is easier to read expanded. |
For the original pairing task, this shorter alternative is also valid:
d = dict(zip(keys, values))
Choose dict(zip(...)) when you only need to pair values. Choose a dictionary comprehension when you need to transform or filter entries:
Cheat Sheet
# Basic form
result = {key: value for item in iterable}
# Pair two iterables
result = {k: v for k, v in zip(keys, values)}
# Transform key and value
result = {k.lower(): v.strip() for k, v in zip(keys, values)}
# Filter entries
result = {k: v for k, v in zip(keys, values) if v is not None}
# Direct pairing, no transformation
result = dict(zip(keys, values))
# Iterate through an existing dictionary
result = {k: v * 2 for k, v in original.items()}
Rules to remember:
- Use
key: value; without the colon, braces create a set comprehension. - Keys must be hashable, such as strings, integers, and tuples.
zip()stops when the shortest input ends.- Repeated keys overwrite earlier values.
- Prefer a normal loop if the comprehension becomes difficult to read.
FAQ
Can I create a dictionary with comprehension syntax in Python?
Yes. Use {key: value for ...}. For paired sequences, write {k: v for k, v in zip(keys, values)}.
What is the difference between a list and dictionary comprehension?
A list comprehension returns values in a list: [expression for item in items]. A dictionary comprehension returns key-value entries: {key: value for item in items}.
Is dict(zip(keys, values)) the same as a dictionary comprehension?
For direct pairing, yes: both create a dictionary and both stop at the shorter sequence. A comprehension is more flexible because it can transform or filter items.
What happens when keys has more items than values?
zip() stops at the end of values, so unmatched keys are omitted.
What happens if a key appears more than once?
The last value for that key wins because dictionaries cannot store duplicate keys.
Can I add an if condition to a dictionary comprehension?
Yes. Put it after the loop: {k: v for k, v in pairs if v > 0}.
Why does fail?
Mini Project
Description
Build a small inventory lookup from two parallel lists: product names and quantities. The result should include only products that are currently in stock. This mirrors a common task when cleaning spreadsheet, CSV, or form data before using it in an application.
Goal
Create a dictionary that maps each in-stock product name to its quantity.
Requirements
Create two lists named products and quantities with matching positions.
Validate that both lists have the same number of items.
Use zip() to pair each product with its quantity.
Use a dictionary comprehension to exclude quantities that are zero or below.
Print the completed inventory dictionary.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.