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.
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)
{}
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
🌐
Python
peps.python.org β€Ί pep-0274
PEP 274 – Dict Comprehensions | peps.python.org
October 25, 2001 - You can use dict comprehensions in ways very similar to list comprehensions, except that they produce Python dictionary objects instead of list objects.
🌐
DataCamp
datacamp.com β€Ί home β€Ί tutorials β€Ί python β€Ί python dictionary comprehension: essentials you need to know
Python Dictionary Comprehension Tutorial | DataCamp
December 4, 2024 - Learn all about Python dictionary comprehension: how you can use it to create dictionaries, to replace (nested) for loops or lambda functions with map(), filter() and reduce(), ...!
🌐
Real Python
realpython.com β€Ί python-dictionary-comprehension
Python Dictionary Comprehensions: How and When to Use Them – Real Python
November 13, 2024 - In dictionary comprehension, the expression must provide the key and its corresponding value, key: value. Both elements can be expressions. The current member: This is the current item or value in the iterable.
🌐
Codecademy
codecademy.com β€Ί article β€Ί what-is-dictionary-comprehension-in-python
What Is Dictionary Comprehension in Python? | Codecademy
... 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.
🌐
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.
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 - 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.
🌐
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 created a dictionary called developers which stores a list of developers with their favorite languages: {'Jane': 'Python', 'Jade': 'JavaScript', 'John': 'Python', 'Doe': 'JavaScript'}. In the dictionary comprehension, we added an expression at the end: if value == 'Python'.
🌐
w3resource
w3resource.com β€Ί python β€Ί python-dictionary-comprehension-with-examples.php
Python Dictionary Comprehensions for Compact Code
April 16, 2026 - The dictionary comprehension iterates over the list 'numbers'. 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' ...
🌐
Switowski
switowski.com β€Ί blog β€Ί dictionary-comprehension
Dictionary Comprehension - Sebastian Witowski
January 19, 2023 - Compared with the old way of passing a list of tuples (in Python 2.6 and below), it's faster and more readable. But it only makes sense to use it when you compute a key or a value on the fly or if you want to do some filtering. If both the key and the value are ready (for example, they come from two different iterables), simply passing the zip() function to dict() results in a much faster and more readable code: # Good use case for dictionary comprehension - we compute the value {i: i * i for i in range(1000)} # Good use case for dictionary comprehension - we compute the key {i * i: i for i in
🌐
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 - Dictionary comprehension is a concise and efficient way to create a dictionary in Python. With dictionary comprehension, elements of an iterable object are transformed into key-value pairs.
🌐
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 - We can use the items of an existing dictionary as iterable in a dictionary comprehension. It allows us to create dictionaries based on existing dictionaries and modify both keys and values.
🌐
Netguru
netguru.com β€Ί home page β€Ί blog β€Ί python dictionary comprehension: syntax, examples & pitfalls
Python dictionary comprehension: syntax, examples & pitfalls
August 14, 2026 - On our own Python services at Netguru, ... Dictionary comprehension is a one-line syntax for building a new dictionary from an iterable, using curly braces around a key: value expression....
🌐
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.
🌐
ListenData
listendata.com β€Ί home β€Ί python
Python Dictionary Comprehension with Examples
It includes various examples which would help you to learn the concept of dictionary comprehension and how it is used in real-world scenarios. ... Like list comprehension, dictionary comprehension lets us to run for loop with a single line of code.
🌐
Learn By Example
learnbyexample.org β€Ί python-dictionary-comprehension
Python Dictionary Comprehension - Learn By Example
April 23, 2020 - In the example above, dictionary comprehension has two parts. 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.
🌐
AlgoMaster
algomaster.io β€Ί home β€Ί python β€Ί dictionary comprehensions
Dictionary Comprehensions | Python | AlgoMaster.io
June 6, 2026 - A dictionary comprehension is Python's one-line form for building a dict from any iterable, with optional filtering and key/value transforms. The shape mirrors a list comprehension, but instead of producing items, each pass produces a key: value ...
🌐
freeCodeCamp
freecodecamp.org β€Ί news β€Ί dictionary-comprehension-in-python-explained-with-examples
Dictionary Comprehension in Python – Explained with Examples
August 24, 2021 - Dictionaries are powerful built-in data structures in Python that store data as key-value pairs. Dictionary Comprehension can be super helpful in creating new dictionaries from existing dictionaries and iterables. In this tutorial, we'll learn ...