This Python code filters a dictionary to extract key-value pairs...

July 1, 2025 at 04:37 PM

# Python3 code to demonstrate working of # Extract dictionary items with List elements # Using all() + dictionary comprehension # initializing dictionary test_dict = {'gfg' : [4, 6], 'is' : [10], 'best' : [9, 5, 7]} # printing original dictionary print("The original dictionary : " + str(test_dict)) # initializing req_list missing_list = [4, 6, 10] # Extract dictionary items with List elements # Using all() + dictionary comprehension res = {key: val for key, val in test_dict.items() if any(vals in missing_list for vals in val)} # printing result print("The extracted dictionary: " + str(res))

This Python code filters a dictionary to extract key-value pairs where at least one element in the list (values of the dictionary) exists in a specified "required" list (missing_list).

Here’s a step-by-step breakdown:


Input

  1. Dictionary (test_dict):

    {'gfg': [4, 6], 'is': [10], 'best': [9, 5, 7]}
    

    Each key has a list of integers as its associated value.

  2. List (missing_list):

    [4, 6, 10]
    

    This is the list of elements we want to search for in the dictionary values.


Code Explanation

  1. Original Dictionary: The original dictionary test_dict is printed.

  2. Dictionary Comprehension:

    res = {key: val for key, val in test_dict.items() if any(vals in missing_list for vals in val)}
    
    • For each key, val pair in test_dict.items(), the code checks if any value (vals) in the list val exists in missing_list (using the any() function).
    • If the condition is True, that key-value pair is included in the new dictionary res.
  3. Result: The resulting dictionary res is printed.


Output

For the given inputs:

  • missing_list: [4, 6, 10]
  • test_dict: {'gfg': [4, 6], 'is': [10], 'best': [9, 5, 7]}

The process works as follows:

  • Key 'gfg': [4, 6] has elements (4, 6) in missing_list. ✅ Included.
  • Key 'is': [10] has element (10) in missing_list. ✅ Included.
  • Key 'best': [9, 5, 7] has no elements in missing_list. ❌ Excluded.

Result:

{'gfg': [4, 6], 'is': [10]}

Final Output:

The original dictionary : {'gfg': [4, 6], 'is': [10], 'best': [9, 5, 7]}
The extracted dictionary: {'gfg': [4, 6], 'is': [10]}
Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node