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 - This helps in building dictionaries directly without writing multiple statements. Example: This example creates a dictionary where numbers from 1 to 5 are used as keys and their squares are stored as values.
🌐
DataCamp
datacamp.com › tutorial › python-dictionary-comprehension
Python Dictionary Comprehension Tutorial | DataCamp
December 4, 2024 - You can read more about the zip() function in this Python example. In our example above, the zip function aggregates the item from fahrenheit.keys() and the celsius list, giving a key-value pair that you can put together in a dictionary using the dict function, which is the desired result. Now, let's try to solve the same problem using dictionary comprehension:
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 - We can now use Python's zip() function to zip these two lists to generate the key-value pairs. Note: The zip function takes in a sequence of iterables as the argument, and returns an iterator of tuples, as shown in the image below. So, the first tuple is the first key-value pair, the second tuple is the second key-value pair, and in general, the i-th tuple is the i-th key-value pair. In this case, the dictionary comprehension takes the following form:
🌐
Dataquest
dataquest.io › home › blog › python dictionary comprehension tutorial (with 39 code examples)
Python Dictionary Comprehension Tutorial (with 39 Examples)
March 6, 2023 - In this tutorial, we'll define dictionary comprehension and go over how you can use it in your own Python projects.
🌐
Real Python
realpython.com › python-dictionary-comprehension
Python Dictionary Comprehensions: How and When to Use Them – Real Python
October 14, 2024 - This way of creating a dictionary from two sequences is pretty Pythonic and straightforward. You don’t need a comprehension. However, if you need to transform the data somehow, then you’d benefit from using a comprehension. For example, say that you have a third list containing the prices of each computer part.
🌐
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 - ... 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): 28} Each pair of items in the lists is a key in the dictionary.
Find elsewhere
🌐
ListenData
listendata.com › home › python
Python Dictionary Comprehension with Examples
Item refers to each element in the iterable you can loop over. Example 1 : Let's say you want to create a dictionary where each number is the key and the value is the square of that number.
🌐
Codecademy
codecademy.com › article › what-is-dictionary-comprehension-in-python
What Is Dictionary Comprehension in Python? | Codecademy
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today. ... Continue your Swift journey by learning these collection types: arrays, sets, and dictionaries! ... Dictionary comprehension is a feature in Python that allows us to build dictionaries in a single, elegant line of code.
🌐
Learn By Example
learnbyexample.org › python-dictionary-comprehension
Python Dictionary Comprehension - Learn By Example
April 23, 2020 - Dictionary comprehensions are also useful for initializing dictionaries from keys lists, in much the same way as the fromkeys() method. Following example Initializes a dictionary with default value ‘0’ for each key.
🌐
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. Dictionary comprehension also allows filtering and modifying key-value pairs based on specified conditions. The syntax for dictionary comprehension looks like the following example:
🌐
Programiz
programiz.com › python-programming › dictionary-comprehension
Python Dictionary Comprehension
In this tutorial, we will learn about Python dictionary comprehension and how to use it with the help of examples. In Python, dictionary comprehension is an elegant and concise way to create dictionaries.
🌐
Python Tutorial
pythontutorial.net › home › python basics › python dictionary comprehension
Python Dictionary Comprehension
March 27, 2025 - stocks = { 'AAPL': 121, 'AMZN': 3380, 'MSFT': 219, 'BIIB': 280, 'QDEL': 266, 'LVGO': 144 } selected_stocks = {} for symbol, price in stocks.items(): if price > 200: selected_stocks[symbol] = price print(selected_stocks) Code language: Python (python) ... How it works. First, iterate over the item of the stocks dictionary....
🌐
YouTube
youtube.com › watch
Python Dictionary Comprehensions - YouTube
Comprehensions are a powerful tool in Python that allow you to create new lists, sets and dictionaries, populated with values. This video explains how Dict c...
Published   May 9, 2023
🌐
Medium
medium.com › @vinodkumargr › list-dictionary-and-set-comprehension-in-python-9823719a67da
LIST , DICTIONARY AND SET COMPREHENSION IN PYTHON | by Vinod Kumar G R | Medium
April 3, 2023 - During this transformation, items within the original dictionary can be conditionally included in the new dictionary and each item can be transformed as needed. ... so the zip( ) function creates an iterator that will aggregate elements from two or more iterables . Keys and values are the iterables that contains iterators(list of data). ... You can try with more examples if you want. ... Set comprehension is a method for creating sets in python using the elements from other iterables like lists, sets, or tuples.
🌐
freeCodeCamp
freecodecamp.org › news › dictionary-comprehension-in-python-dict-comprehensions-explained
Dictionary Comprehension in Python – Dict Comprehensions Explained
September 16, 2022 - In the example above, we added a string to every key in the dictionary comprehension: key + ' in meters'. In this section and the next, you'll learn about other expressions that you can use to modify the items stored in dictionaries created ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python dictionary comprehension explained
Python Dictionary Comprehension Explained - Spark By {Examples}
May 31, 2024 - Python dictionary comprehension is used to create dictionaries using iterable. A dictionary in Python is a collection that is unordered, mutable, and does
🌐
Devcuriosity
devcuriosity.com › manual › details › python-dict-comprehensions
Python - Dictionary (Dict) Comprehensions with examples
For the sake of completeness, please take a look at a note about Python List Comprehensions because they are very similar. my_dict = {str(x): x for x in range(1, 6)} print(my_dict) # {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5} ... This is one of the simplest examples of dict comprehension.
🌐
Python
peps.python.org › pep-0274
PEP 274 – Dict Comprehensions | peps.python.org
October 25, 2001 - Dict comprehensions are just like list comprehensions, except that you group the expression using curly braces instead of square braces. Also, the left part before the for keyword expresses both a key and a value, separated by a colon. The notation is specifically designed to remind you of list comprehensions as applied to dictionaries.
🌐
w3resource
w3resource.com › python › python-dictionary-comprehension-with-examples.php
Python Dictionary Comprehensions for Compact Code
April 16, 2026 - Just like list comprehensions, dictionary comprehensions can include an if condition to filter out certain items. ... This example demonstrates how to create a dictionary of squares for even numbers only using dictionary comprehension with a filter.