I am working on a python project, I am creating a subset dictionary from the main dictionary, the subset dictionary only takes the key, value pairs that are under keys: ‘E’, ‘O’, ‘L’.
I found this code is working perfectly:
{key: self._the_main_dict[key] for key in self._the_main_dict.keys() & {'E', 'O', 'L'}}
However, I would like to understand how it works, can anyone please explain it in multiple lines of code, I guess it is something like: for key in ….
>Solution :
In short python has comprehensions that can provide one liner for datatype construction using for loops.
Here, this is an example of dictionary comprehension.
{key: self._the_main_dict[key] for key in self._the_main_dict.keys() & {'E', 'O', 'L'}}
This code can be extended to:
output = dict()
for key in self._the_main_dict.keys() & {'E', 'O', 'L'}:
output[key] = self._the_main_dict[key]
output is the response provided by above dictionary comprehension.
self._the_main_dict.keys() & {'E', 'O', 'L'}. If you’re confused on this. This is just an Intersection operation between two sets. Yeah! Sets and Venn diagram you used to study in mathematics 😀