Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need help to understand an one line code that extract subset dictionary with selected key and value pairs

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 ….

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 😀

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading