Python program to extract dictionary items for custom values

Python program to extract dictionary items for custom values

Let's go step by step.

Objective:

Given a dictionary and a list of values, extract the key-value pairs from the dictionary where the value matches one in the list of values.

Example:

For the dictionary:

{'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4} 

and the list of values:

[1, 3] 

The result will be:

{'apple': 1, 'cherry': 3} 

Python Program:

def extract_items_for_values(dictionary, values_list): # Use dictionary comprehension to filter items with values in values_list return {k: v for k, v in dictionary.items() if v in values_list} # Test the function sample_dict = {'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4} values_to_extract = [1, 3] result = extract_items_for_values(sample_dict, values_to_extract) # Print the results print(f"Original Dictionary: {sample_dict}") print(f"Extracted Items for Values {values_to_extract}: {result}") 

When you run the program, you'll get:

Original Dictionary: {'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4} Extracted Items for Values [1, 3]: {'apple': 1, 'cherry': 3} 

Explanation:

  1. We define a function extract_items_for_values that takes a dictionary (dictionary) and a list of values (values_list) as arguments.
  2. Inside the function, we use dictionary comprehension to iterate over the items of the dictionary. For each key-value pair, we check if the value is in values_list using the in keyword.
  3. The function returns a new dictionary containing only the key-value pairs where the value matches one in the list.
  4. We then test the function with a sample dictionary and list of values, then print the results.

This method efficiently filters the dictionary's items based on the given list of values.


More Tags

angular-forms jquery-cookie webcam.js android-signing sqltools 2d wamp pgp dto expirationhandler

More Programming Guides

Other Guides

More Programming Examples