Dictionary Comprehension
Last Updated: 07-11-2017
Python Dictionary Comprehension
Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}
Let’s see a example,lets assume we have two lists named keys and value now,
Output :
We can also make dictionary from a list using comprehension
Output :
and like,
Output :
We can use Dictionary comprehensions with if and else statements and with other expressions too. This example below maps the numbers to their cubes that are not divisible by 4:
Output :
This article is contributed by Shantanu Sharma.. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Reference : https://www.geeksforgeeks.org/python-dictionary-comprehension/
Last updated