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,
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.
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!