This Python code demonstrates how to extract items from a...
This Python code demonstrates how to extract items from a dictionary where the corresponding list values do not contain any elements from a given "missing_list". Here's a detailed explanation:
-
Dictionary Initialization:
test_dict = {'gfg' : [4, 6], 'is' : [10], 'best' : [4, 5, 7]}
The dictionary
test_dict
is initialized with string keys and list values. -
Printing the Original Dictionary: The original dictionary is printed to show the data before processing.
-
Defining the List to Check (
missing_list
):missing_list = [4, 6, 10]
This list contains the elements you want to check against the values of the dictionary. The goal is to exclude any dictionary items where any of the list elements from
missing_list
are found in the corresponding list values of the dictionary. -
Extracting the Filtered Dictionary Items:
res = {key: val for key, val in test_dict.items() if not any(vals in missing_list for vals in val)}
- A dictionary comprehension is used to filter
test_dict
. - For each key-value pair (
key
,val
) in the dictionary:- The condition
not any(vals in missing_list for vals in val)
is checked. - This uses the
any()
function, which checks if any element in the listval
is present inmissing_list
. - If
any()
returnsFalse
(i.e., none of the values inval
are inmissing_list
), the key-value pair is kept in the resulting dictionary.
- The condition
- A dictionary comprehension is used to filter
-
Printing the Result: The filtered dictionary
res
is printed. It contains only the dictionary items where no elements in the list values appear inmissing_list
.
Output Example:
Given the input:
test_dict = {'gfg' : [4, 6], 'is' : [10], 'best' : [4, 5, 7]}
missing_list = [4, 6, 10]
- Iteration over
test_dict
:- For
'gfg': [4, 6]
: Both 4 and 6 are inmissing_list
, so this key-value pair is excluded. - For
'is': [10]
: 10 is inmissing_list
, so this key-value pair is excluded. - For
'best': [4, 5, 7]
: 4 is inmissing_list
, so this key-value pair is excluded.
- For
Thus, the final result is an empty dictionary:
"The extracted dictionary: {}"