Here is how to do dictionary comprehension in Python.


words = ['be', 'is', 'are'] 
word_length = {word: len(word) for word in words} 
print(word_length) 

Output

{'be': 2, 'is': 2, 'are': 3}


Explanation
A dictionary comprehension is a code expression that constructs a dictionary out of an original object. In this case, the original object is a list. The dictionary comprehension is constructing a dictionary that contains (1) the items of the list as keys and (2) the length of those items (i.e., number of characters) as value. 


Related HowTos
Schedule a Python script for execution at a specific time every day
Store Python passwords securely on Windows, Mac, and Linux
Do list comprehension
Create a virtual environment
Create a new file
Merge two lists
Extract items from two different lists into one list
Check if a text file is empty
Randomly select an item from a list
Generate a random integer
Break a while loop
Create a pandas DataFrame from a dictionary
Create a pandas DataFrame from a list
Get the last item of a list
Delete a column from a pandas dataframe
Access a column of a pandas dataframe
Create a class
Make a webpage request
Get the first two characters of a string
<django.db.models.fields.CharField>
Recommended Course

Learn Flask development and learn to build cool apps with our premium Python course on Udemy.


Mailing List

We will keep you Python-motivated if you subscribe below.