How to create a dictionary comprehension in Python


In Python programming, dictionary comprehension is an efficient way of writing code to create a new dict using expression to generate keys and values.

Let's take a look at an example to make it easy to understand.

multiplication_table_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#table of 2
squared_dict = {no: no*2 for no in multiplication_table_list}

print(squared_dict)
Output:
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18, 10: 20}

Here we have a list of numbers from 1 to 10 that will be used to create a dict of the multiplication table of 2.

Note: Using each iteration we used the number as both the key and the value expression.

create a dictionary comprehension in Python example

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap