There are dictionary comprehensions in Python 2.7+, but they don't work quite the way you're trying. Like a list comprehension, they create a new dictionary; you can't use them to add keys to an existing dictionary. Also, you have to specify the keys and values, although of course you can specify a dummy value if you like.

>>> d = {n: n**2 for n in range(5)}
>>> print d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

If you want to set them all to True:

>>> d = {n: True for n in range(5)}
>>> print d
{0: True, 1: True, 2: True, 3: True, 4: True}

What you seem to be asking for is a way to set multiple keys at once on an existing dictionary. There's no direct shortcut for that. You can either loop like you already showed, or you could use a dictionary comprehension to create a new dict with the new values, and then do oldDict.update(newDict) to merge the new values into the old dict.

Answer from BrenBarn on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-dictionary-comprehension
Python Dictionary Comprehension - GeeksforGeeks
April 18, 2026 - Dictionary comprehension is used to create a dictionary in a short and clear way. It allows keys and values to be generated from a loop in one line.
🌐
Real Python
realpython.com › python-dictionary-comprehension
Python Dictionary Comprehensions: How and When to Use Them – Real Python
October 14, 2024 - To build this dictionary, you compute the key-value pairs from the items of an input iterable. Note that the syntax includes an optional conditional at the end, which you can use to filter existing dictionaries.
Discussions

Why does dict.fromkeys() pass by reference instead of making copies?
python has no concept of "passing by value" in the way you are thinking. This behaviour is global everywhere in the language. Everything is an object which under the hood points to a specific object. More on reddit.com
🌐 r/learnpython
15
4
May 31, 2024
Why don't we have tuple comprehension?
You can do tuple(x**2 for x in range(5)) if you wish. But tuples are intended to be used with fixed length and not for iterating over (though Python allows this). More on reddit.com
🌐 r/learnpython
47
39
December 20, 2023
At what point are loops better than list comprehensions?
Readability is important, just after correctness. That means, in the initial approximation, speed/efficiency is less important. Until much later anyway. I wouldn't try to write that code as a comprehension. If, later, you need faster code you worry about algorithms first, not the low-level stuff. More on reddit.com
🌐 r/learnpython
56
32
September 19, 2023
This is so hard
First off let me say, if you don’t have this feeling when you’re learning to code, you’re not trying hard enough. Every person here has felt like the dumbest person in the world when learning to code. But there’s a joke I was told that no one really knows how to code except for like 10 people who post on stackoverflow. So don’t feel bad if you have to look stuff up. I’ve been programming for almost 3 years and I sometimes have to look up the simplest stuff. It happens. As far as csv files and all that data science-y stuff goes feel free to DM me with questions bc I love that shit and I don’t get to do enough of it at my job (email dev so I barely use python until someone wants their outlook automated) But you’ll get better More on reddit.com
🌐 r/learnpython
92
137
July 17, 2023
Top answer
1 of 9
713

There are dictionary comprehensions in Python 2.7+, but they don't work quite the way you're trying. Like a list comprehension, they create a new dictionary; you can't use them to add keys to an existing dictionary. Also, you have to specify the keys and values, although of course you can specify a dummy value if you like.

>>> d = {n: n**2 for n in range(5)}
>>> print d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

If you want to set them all to True:

>>> d = {n: True for n in range(5)}
>>> print d
{0: True, 1: True, 2: True, 3: True, 4: True}

What you seem to be asking for is a way to set multiple keys at once on an existing dictionary. There's no direct shortcut for that. You can either loop like you already showed, or you could use a dictionary comprehension to create a new dict with the new values, and then do oldDict.update(newDict) to merge the new values into the old dict.

2 of 9
175

You can use the dict.fromkeys class method ...

>>> dict.fromkeys(range(5), True)
{0: True, 1: True, 2: True, 3: True, 4: True}

This is the fastest way to create a dictionary where all the keys map to the same value.

But do not use this with mutable objects:

d = dict.fromkeys(range(5), [])
# {0: [], 1: [], 2: [], 3: [], 4: []}
d[1].append(2)
# {0: [2], 1: [2], 2: [2], 3: [2], 4: [2]} !!!

If you don't actually need to initialize all the keys, a defaultdict might be useful as well:

from collections import defaultdict
d = defaultdict(lambda: True)

To answer the second part, a dict-comprehension is just what you need:

{k: k for k in range(10)}

You probably shouldn't do this but you could also create a subclass of dict which works somewhat like a defaultdict if you override __missing__:

>>> class KeyDict(dict):
...    def __missing__(self, key):
...       #self[key] = key  # Maybe add this also?
...       return key
... 
>>> d = KeyDict()
>>> d[1]
1
>>> d[2]
2
>>> d[3]
3
>>> print(d)
{}
🌐
freeCodeCamp
freecodecamp.org › news › dictionary-comprehension-in-python-explained-with-examples
Dictionary Comprehension in Python – Explained with Examples
August 24, 2021 - Let's say we already have a Python dictionary. 📚 · However, we'd like to create a new dictionary that contains only the items from our dictionary that satisfy a particular condition. Dictionary Comprehension can be really handy in doing this. <dict_name> = {<new_key>:<new_value> for (key,value) in <dict>.items() if <condition>} Let's parse the above syntax.
🌐
DataCamp
datacamp.com › tutorial › python-dictionary-comprehension
Python Dictionary Comprehension Tutorial | DataCamp
December 4, 2024 - Dictionary comprehension is a concise and readable way to create dictionaries in Python. It provides a way to create a new dictionary from an iterable object like a list, tuple, or set. The syntax for dictionary comprehension in Python is as follows: {key:value for (key,value) in iterable}
🌐
Programiz
programiz.com › python-programming › dictionary-comprehension
Python Dictionary Comprehension
As we can see, only the items with even value have been added, because of the if clause in the dictionary comprehension. To learn more about if clause, visit Python if...else.
🌐
Python
peps.python.org › pep-0274
PEP 274 – Dict Comprehensions | peps.python.org
October 25, 2001 - In Python 2.2, the dict() constructor accepts an argument that is a sequence of length-2 sequences, used as (key, value) pairs to initialize a new dictionary object. However, the act of turning some data into a sequence of length-2 sequences can be inconvenient or inefficient from a memory or performance standpoint. Also, for some common operations, such as turning a list of things into a set of things for quick duplicate removal or set inclusion tests, a better syntax can help code clarity. As with list comprehensions, an explicit for loop can always be used (and in fact was the only way to do it in earlier versions of Python).
Find elsewhere
🌐
Codecademy
codecademy.com › article › what-is-dictionary-comprehension-in-python
What Is Dictionary Comprehension in Python? | Codecademy
Let’s walk through the parameters of dictionary comprehension: key_expression: Determines each key in the dictionary. value_expression: Defines the value associated with each key. if (Optional): Filters which items are included in the dictionary. Now that we know the syntax of dictionary comprehension let’s use it to create a dictionary.
🌐
Towards Data Science
towardsdatascience.com › home › latest › 10 examples to master python dictionary comprehensions
10 Examples to Master Python Dictionary Comprehensions | Towards Data Science
January 18, 2025 - Dictionary comprehensions allow for generating keys of tuples by implemented nested loops. ... print(dct) {(1, 5): 5, (1, 6): 6, (1, 7): 7, (2, 5): 10, (2, 6): 12, (2, 7): 14, (3, 5): 15, (3, 6): 18, (3, 7): 21, (4, 5): 20, (4, 6): 24, (4, 7): ...
🌐
PhoenixNAP
phoenixnap.com › home › kb › devops and development › python dictionary comprehension explained
Python Dictionary Comprehension Explained | phoenixNAP KB
April 17, 2025 - Dictionary comprehension is a technique for creating Python dictionaries in one line. The method creates dictionaries from iterable objects, such as a list, tuple, or another dictionary.
🌐
Analytics Vidhya
analyticsvidhya.com › home › python dictionary comprehension: mastering data manipulation with precision
Python Dictionary Comprehension: Mastering Data Manipulation with Precision
May 27, 2025 - Here are some methods and examples of using dictionary comprehension in Python: Dictionary comprehension follows the syntax `{key: value for (key, value) in iterable}`. It iterates over each item in the iterable and constructs a dictionary where ...
🌐
Python Tutorial
pythontutorial.net › home › python basics › python dictionary comprehension
Python Dictionary Comprehension
March 27, 2025 - A dictionary comprehension allows you to run a for loop on a dictionary and do something on each item like transforming or filtering and returns a new dictionary. Unlike a for loop, a dictionary comprehension offers a more expressive and concise syntax when you use it correctly.
🌐
Mimo
mimo.org › glossary › python › dictionary-comprehension
Python Dictionary Comprehension: Syntax, Usage, and Examples
Create dictionaries fast with Python dictionary comprehension using {key: value for ...} syntax, letting you transform and filter key-value pairs and build lookup tables in a single readable line.
🌐
Learn By Example
learnbyexample.org › python-dictionary-comprehension
Python Dictionary Comprehension - Learn By Example
April 23, 2020 - The first part collects the key/value results of expressions on each iteration and uses them to fill out a new dictionary. The second part is exactly the same as the for loop, where you tell Python which iterable to work on.
🌐
Toppr
toppr.com › guides › python-guide › references › methods-and-functions › dictionary-comprehension › python-dictionary-comprehension
What is Python Dictionary Comprehension? | Definition and Examples
July 20, 2021 - We can also have multiple if conditions in the same line of dictionary comprehension syntax code. ... # Python program to illustrate multiple if statements in dict comprehension car_rank = {'Ferrari': 1, 'Audi': 2, 'Porsche': 3, 'BMW': 4, 'Tata': 5, 'Jaguar': 6, 'Toyota': 7, 'Honda': 8, 'GM': 9, 'Land Rover': 10} sep_rank = {k: v for (k, v) in car_rank.items() if v % 2 == 0 if v < 10} print('Top Even ranking Car Brands below 10: ', sep_rank)
🌐
freeCodeCamp
freecodecamp.org › news › dictionary-comprehension-in-python-dict-comprehensions-explained
Dictionary Comprehension in Python – Dict Comprehensions Explained
September 16, 2022 - In this section and the next, you'll learn about other expressions that you can use to modify the items stored in dictionaries created using dictionary comprehension. We'll start with conditional statements. developers = {'Jane': 'Python', 'Jade': 'JavaScript', 'John': 'Python', 'Doe': 'JavaScript'} python_developers = {key: value for (key, value) in developers.items() if value == 'Python'} print(python_developers) # {'Jane': 'Python', 'John': 'Python'}
🌐
OpenStax
openstax.org › books › introduction-python-programming › pages › 10-5-nested-dictionaries-and-dictionary-comprehension
10.5 Nested dictionaries and dictionary comprehension - Introduction to Python Programming | OpenStax
March 13, 2024 - Here is a general syntax for dictionary comprehension: {key_expression: value_expression for element in iterable} ... names = ["Alice ", "Bob ", "Charlie "] name_lengths = {name: len(name) for name in names} print(name_lengths) ...
🌐
Netguru
netguru.com › home page › blog › python basics: list comprehensions, dictionary comprehensions and generator expressions
Python Basics: List Comprehensions, Dictionary Comprehensions and Generator Expressions
September 28, 2023 - They provide an elegant method ... that used for list comprehension, namely {key: item-expression for item in iterator}, but note the inclusion of the expression pair (key:value)....
🌐
Dataquest
dataquest.io › home › blog › python dictionary comprehension tutorial (with 39 code examples)
Python Dictionary Comprehension Tutorial (with 39 Examples)
March 6, 2023 - Values come second, so the index should be 1, while for keys it would be 0. Keys are usually assigned to lambda functions which are anonymous functions often used in Python. Do you think it is possible to apply a for loop to achieve the same result? Sometimes we face a list of dictionaries, and we want one single dictionary. It can also be done with dictionary comprehension.