This Python code extracts key-value pairs from a dictionary where...

July 1, 2025 at 04:35 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' : [4, 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 extracts key-value pairs from a dictionary where the values (lists) contain at least one element from a specified list (missing_list). Here's a step-by-step explanation:

Code Breakdown:

  1. Original Dictionary:

    • The dictionary test_dict is defined as:
      test_dict = {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
      
    • It contains keys ('gfg', 'is', 'best') with lists as their associated values.
  2. Specified List:

    • The list missing_list is defined as:
      missing_list = [4, 6, 10]
      
    • This list contains the elements that are being checked against the lists in test_dict.
  3. Dictionary Comprehension with any():

    • The following dictionary comprehension is used to filter the key-value pairs:
      res = {key: val for key, val in test_dict.items() if any(vals in missing_list for vals in val)}
      
    • Step-by-step breakdown of how this works:
      • Iterate over the items (key, val) of test_dict.
      • For each val (a list), check if any element (vals) of val exists in missing_list using the any() function:
        any(vals in missing_list for vals in val)
        
        This returns True if at least one element from val is in missing_list.
      • If True, include that key: val pair in the result dictionary res.
  4. Result:

    • The code builds a new dictionary res containing only the key-value pairs that satisfy the condition.

Output:

  • The original dictionary is:
    The original dictionary : {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
    
  • The filtered dictionary res is:
    The extracted dictionary: {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
    
  • Explanation of the result:
    • 'gfg': [4, 6] → Contains both 4 and 6 (both in missing_list).
    • 'is': [10] → Contains 10 (in missing_list).
    • 'best': [4, 5, 7] → Contains 4 (in missing_list).

Thus, the code effectively extracts all key-value pairs where the lists in the dictionary contain at least one element from missing_list.

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