How to understand a one-line code that extract subset dictionary with selected key and value pairs

Question:

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. How could this be expressed in multiple lines of code? I guess it is something like: for key in ….

Asked By: Poca

||

Answers:

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 😀

Answered By: PaxPrz

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'}}
Answered By: Jan Wilamowski

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'}}
Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.