Showing posts with label dictionary comprehension. Show all posts
Showing posts with label dictionary comprehension. Show all posts

Jul 3, 2020

Dictionary Comprehensions | Dictionary in Python | Coding Winds

Dictionary Comprehension

Hello guys, here we will talk about dictionary comprehension.

Dictionary comprehension is a precise way to create a new dictionary from the existing dictionary in python

Syntax is,

{key: expression for x in iterable if conditional}

Output

Another example,

Output

Single If statement

Output

We see that the conditional statement worked properly.

Similarly we can use multiple If loop and if-else also.

Nested dictionary with two dictionary comprehensions

Output

This code without dictionary comprehension will look like this,

We must be careful while using dictionary comprehension as:

1)     They can sometimes make the code run slower and consume more memory.

2)     They can also decrease the readability of the code.


  Hello Python people, for this blog we have taken help from the book Python : The Complete Reference.

Hope all your doubts regarding this are clear now.

If you still have any doubt on this topic then do come to us via email "sophomoretechs@gmail.com" or via Instagram "@coding.winds".


Do subscribe to our daily blog update by clicking here.


Thank You!