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

Time:09-16

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

CodePudding user response:

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 :D

CodePudding user response:

The keys() method returns a set-like object containing the keys of the dictionary. Sets use the & operator to perform intersection, so

self._the_main_dict.keys() & {'E', 'O', 'L'}

is equivalent to

self._the_main_dict.keys().intersection({'E', 'O', 'L'})

and returns the subset of the keys that are in the {'E', 'O', 'L'} set.

Then the rest of the dictionary comprehension creates a new dictionary containing key: self._the_main_dict[key] for those keys.

A more common way to write this would be:

{key: self._the_main_dict[key] 
    for key in self._the_main_dict.keys() 
    if key in {'E', 'O', 'L'}}

CodePudding user response:

This works by creating an intersection of the dict's keys with the set containing E, O and L. In long form, this could be written as:

all_keys = self._the_main_dict.keys()
keys_of_interest = {'E', 'O', 'L'}
filtered_keys = all_keys & keys_of_interest
# alternatively:
filtered_keys = keys_of_interest.intersection(all_keys)

These keys are then iterated over to create the resulting dict via a dictionary comprehension. A clearer way would be to explicitly specify the condition rather than implicitly through the merging step:

{key: self._the_main_dict[key] for key in self._the_main_dict.keys() if key in {'E', 'O', 'L'}}
  • Related