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 - Example 1: This example demonstrates creating a dictionary by transforming and repeating characters from a string. ... We can include conditions in a dictionary comprehension to filter items or apply logic only to specific values.
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)
{}
Discussions

python - Create a dictionary with comprehension - Stack Overflow
I like the Python list comprehension syntax. Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values: More on stackoverflow.com
๐ŸŒ stackoverflow.com
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?
The nesting is a red herring. Deeply nested comprehensions actually look pretty tidy, since they prevent the indentation from getting out of control. The real issue here is that the code is an unreadable mess, and if you clean it up you'll quickly realize that a list comprehension isn't suitable for it. for entry in lst: related_entities = entry[0]["relatedEntities"] if related_entities is None: continue for entity in related_entities: for item in entity.keys() & list_of_fields: unpacked.append({ "filingNumberDisplay": entry[0]["serials"][0]["filingNumberDisplay"], "id": entity[item], }) More on reddit.com
๐ŸŒ r/learnpython
56
32
September 19, 2023
People also ask

What is the syntax for dictionary comprehension in Python?

The syntax for dictionary comprehension in Python is as follows: {key:value for (key,value) in iterable}

๐ŸŒ
datacamp.com
datacamp.com โ€บ home โ€บ tutorials โ€บ python โ€บ python dictionary comprehension: essentials you need to know
Python Dictionary Comprehension Tutorial | DataCamp
What are the benefits of using dictionary comprehension in Python?

The benefits of using dictionary comprehension in Python are that it is concise, readable, and reduces the amount of code needed to create dictionaries. It also allows for filtering and transformation of dictionary elements in a single line of code.

๐ŸŒ
datacamp.com
datacamp.com โ€บ home โ€บ tutorials โ€บ python โ€บ python dictionary comprehension: essentials you need to know
Python Dictionary Comprehension Tutorial | DataCamp
How do I create a dictionary from a list using dictionary comprehension in Python?

You can create a dictionary from a list using dictionary comprehension in Python by iterating over the list and setting the list elements as keys and values in the new dictionary.

๐ŸŒ
datacamp.com
datacamp.com โ€บ home โ€บ tutorials โ€บ python โ€บ python dictionary comprehension: essentials you need to know
Python Dictionary Comprehension Tutorial | DataCamp
๐ŸŒ
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:
๐ŸŒ
DataCamp
datacamp.com โ€บ home โ€บ tutorials โ€บ python โ€บ python dictionary comprehension: essentials you need to know
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:
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ dictionary-comprehension
Python Dictionary Comprehension | Programiz
January 17, 2024 - Dictionaries are data types in Python which allows us to store data in key/value pair. For example: ... Dictionary comprehension is an elegant and concise way to create dictionaries.
๐ŸŒ
Codecademy
codecademy.com โ€บ article โ€บ what-is-dictionary-comprehension-in-python
What Is Dictionary Comprehension in Python? | Codecademy
Learn the basics of Python 3.13, 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.
Find elsewhere
๐ŸŒ
Dataquest
dataquest.io โ€บ home โ€บ blog โ€บ python dictionary comprehension tutorial (with 39 code examples)
Python Dictionary Comprehension Tutorial (with 39 Examples)
March 6, 2023 - Another use of dictionary comprehension in Python is dictionary sorting. For example, let's say we want to sort the dictionary with game titles and years by year from the first to the latest year?
๐ŸŒ
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.
๐ŸŒ
Real Python
realpython.com โ€บ python-dictionary-comprehension
Python Dictionary Comprehensions: How and When to Use Them โ€“ Real Python
November 13, 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.
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ dictionary-comprehension-python
Python Dictionary Comprehension with Examples | FavTutor
July 3, 2026 - Learn Python dictionary comprehension in one line: build a dict from a list, two lists with zip, filter with if, and swap keys and values.
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ artificial intelligence โ€บ 10 examples to master python dictionary comprehensions
10 Examples to Master Python Dictionary Comprehensions | Towards Data Science
January 2, 2021 - ... 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.
๐ŸŒ
w3resource
w3resource.com โ€บ python โ€บ python-dictionary-comprehension-with-examples.php
Python Dictionary Comprehensions for Compact Code
April 16, 2026 - For each number 'x', it checks if the number is even or odd using the condition 'x % 2 == 0'. Depending on the result, it assigns either 'Even' or 'Odd' as the value in the 'even_odd' dictionary.
๐ŸŒ
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 ...
๐ŸŒ
Python Guides
pythonguides.com โ€บ python-dictionary-comprehension
Python Dictionary Comprehension
August 18, 2025 - Learn Python dictionary comprehension with step-by-step examples. Create, filter, and transform dictionaries easily using one-liners in Python for learning.
๐ŸŒ
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.
๐ŸŒ
SitePoint
sitepoint.com โ€บ python hub โ€บ dictionary comprehension
Python - Dictionary Comprehension | SitePoint โ€” SitePoint
For the string "PYTHON", enumerate(word) will produce: [(0, 'P'), (1, 'Y'), (2, 'T'), (3, 'H'), (4, 'O'), (5, 'N')] The comprehension iterates over each tuple (index, char) produced by enumerate(word). For each tuple (index, char), the dictionary stores char (the character) as the key and index (its position in the string) as the value. ๐Ÿ“Œ Example 2: Mathematical expressions.
๐ŸŒ
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.
๐ŸŒ
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) ...
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ artificial intelligence โ€บ dictionary comprehensions in python
Dictionary Comprehensions in Python | Towards Data Science
November 13, 2020 - For example, if we only want numbers with an even count in our dictionary, we can use the following code: ... As we can see, we added an if statement after the for loop within the dictionary comprehension. If the count of the current number is even, we add the corresponding key:value pair to our dictionary. Otherwise, we don't add that key:value pair to our dictionary. Three Concepts to Become a Better Python Programmer