List and Dictionary Comprehensions Made Easy
In my day job as a Python developer, I use list and dictionary comprehensions quite regularly. They also come in handy during live coding tests for an interview.
List Comprehensions
The way I remember a list comprehension is simply:
[x for x in list]
If you can remember this, then you can adapt it to do whatever you want.
1) You can modify the first x
int_list = [1, 2, 3, 4][x + 1 for x in int_list]
Returns: [2, 3, 4, 5]
2) You can add conditional logic (an if statement)
[x for x in int_list if x > 2]
Returns: [3, 4]
3) You can use and/or
in your if statement
[x for x in int_list if x < 2 or x > 3]
Returns: [1, 4]
4) You can even use a function inside the list comprehension
def add_three(i):
return i + 3[add_three(x) for x in int_list]
Returns: [4, 5, 6, 7]
So if you just remember the basics, it’s not so hard to build off it.
Dictionary Comprehensions
Dictionary comprehensions are very similar.
Just remember:
{k:v for k,v in my_dict.items()}
The key here is remembering items()
which returns a list of key-value pairs.
Again, you can adapt this to do all sorts of handy things.
1) You can modify the values
a_dict = {"a":1, "b":2, "c":3}{k:v+1 for k,v in a_dict.items()}
Returns: {'a': 2, 'b': 3, 'c': 4}
2) You can modify the keys
{k+k:v for k,v in a_dict.items()}
Returns: {'aa': 1, 'bb': 2, 'cc': 3}
3) You can add an if statement for the values
{k:v for k,v in a_dict.items() if v > 1}
Returns: {'b': 2, 'c': 3}
4) You can add an if statement for the keys
{k:v for k,v in a_dict.items() if k.startswith("a")}
Returns: {'a': 1}
5) You can use and/or
in your if statement
{k:v for k,v in a_dict.items() if v > 1 and v < 3}
Returns: {'b': 2}
6) You can even use a function inside the dictionary comprehension
def add_three(i):
return i + 3{k:add_three(v) for k,v in my_dict.items()}
Returns: {'a': 4, 'b': 5, 'c': 6}
So you can see that list and dictionary comprehensions are very simple. If you just memorize the basic forms, then it’s pretty easy to create variations of them to suit your needs.
Have fun and stay pythonic.
Here’s a video I made about the topic:
If you love python, and you know you do, check out my YouTube channel and my other medium stories.