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)
{}
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ datastructures.html
5. Data Structures โ€” Python 3.14.6 documentation
The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.
๐ŸŒ
Switowski
switowski.com โ€บ blog โ€บ dictionary-comprehension
Dictionary Comprehension
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
๐ŸŒ
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.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-dictionary-comprehension
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(), ...!
๐ŸŒ
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.
Find elsewhere
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_lists_comprehension.asp
Python - List Comprehension
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
๐ŸŒ
Yardsale8
yardsale8.github.io โ€บ stat489_book โ€บ AssociativeDataStructures_DictionariesAndSets โ€บ Comprehensions.html
5.3. Dictionary and Set Comprehensions โ€” Runestone Interactive Overview
A list comprehension is delimited by brackets ('[',']') not braces ('{', '}'). ... The dictionary comprehension can be identified by the surrounding braces and the key-value pair in the operation expression.
๐ŸŒ
Real Python
realpython.com โ€บ python-dictionary-comprehension
Python Dictionary Comprehensions: How and When to Use Them โ€“ Real Python
October 14, 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.
๐ŸŒ
SitePoint
sitepoint.com โ€บ python hub โ€บ dictionary comprehension
Python - Dictionary Comprehension | SitePoint โ€” SitePoint
A dictionary comprehension is a concise way to create dictionaries in Python by specifying key-value pairs inside curly braces {} using a single line of code.
๐ŸŒ
CS50
cs50.harvard.edu โ€บ python โ€บ shorts โ€บ list_dictionary_comprehensions
List and Dictionary Comprehension - CS50's Introduction to Programming with Python
Interested in a verified certificate or a professional certificate ยท David J. Malan malan@harvard.edu Facebook GitHub Instagram LinkedIn Reddit Threads Twitter
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ dictionary-comprehension-in-python-dict-comprehensions-explained
Dictionary Comprehension in Python โ€“ Dict Comprehensions Explained
September 16, 2022 - You can use Dictionaries in Python to store data in key and value pairs. And you can use dictionary comprehension to create a new dictionary from an already existing one. When creating a new dictionary using dictionary comprehension, you can perfor...
๐ŸŒ
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 - Keys and values are the iterables ... if you want. ... Set comprehension is a method for creating sets in python using the elements from other iterables like lists, sets, or tuples....
๐ŸŒ
NobleBank
noblebank.com
Local Community Banking in Central Alabama | NobleBank & Trust
NobleBank & Trust offers the best financial accounts & services in the Birmingham, Al area. From personal to business banking services, we offer it all!
Price ย  $$
Call ย  (256) 741-1800
Address ย  1509 Quintard Ave, 36201, Anniston
๐ŸŒ
James' Coffee Blog
jamesg.blog โ€บ 2024 โ€บ 01 โ€บ 17 โ€บ dictionary-comprehension
A comprehensive guide to Python dictionary comprehensions - James' Coffee Blog
The Python dictionary comprehension lets you create a dictionary using an iterable. You can also change values or filter values in an existing dictionary. Comprehensions can be on one line, allowing you to concisely represent some logic.
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
Python-Fiddle
python-fiddle.com โ€บ tutorials โ€บ dict-comprehension
Dictionary comprehension is a concise way to create dictionaries in Python.
Dictionary comprehension is a concise way to create dictionaries in Python. It allows us to create a new dictionary by performing operations on existing iterables, such as lists or other dictionaries. Dictionary comprehension is similar to [list comprehension](/tutorials/list-comprehension), ...
๐ŸŒ
Alma Better
almabetter.com โ€บ bytes โ€บ tutorials โ€บ python โ€บ dictionary-comprehension-python
Dictionary Comprehension in Python
April 25, 2024 - Dictionary comprehension could be a Python feature that makes a new dictionary from an iterable object employing a brief syntax.