Python - Extract dictionary items with List elements
Last Updated :
10 May, 2023
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the items from dictionary that constitute all the elements from a list. This kind of problem can occur in domains such as competitive programming and web development. Let's discuss certain ways in which this task can be performed.
Input : test_dict = {'gfg' : [4, 6, 10], 'is' : [12]}
Output : {'gfg': [4, 6, 10]}
Input : test_dict = {'gfg' : [4, 6, 10]}
Output : {'gfg': [4, 6, 10]}
Method #1 : Using set() + dictionary comprehension + items()
The combination of above functionalities can be used to solve this problem. In this, we first reduce the list elements to remove duplicate, extract dictionary items using items() and construction of required dictionary happens using dictionary comprehension.
Python3
# Python3 code to demonstrate working of
# Extract dictionary items with List elements
# Using set() + dictionary comprehension + items()
# helpr_fnc
def hlper_fnc(req_list, test_dict):
temp = set(req_list)
temp2 = { key: set(val) for key, val in test_dict.items() }
return { key: val for key, val in test_dict.items() if temp2[key].issubset(temp)}
# 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
req_list = [4, 6, 10]
# Extract dictionary items with List elements
# Using set() + dictionary comprehension + items()
res = hlper_fnc(req_list, test_dict)
# printing result
print("The extracted dictionary: " + str(res))
Output :
The original dictionary : {'is': [10], 'best': [4, 5, 7], 'gfg': [4, 6]}
The extracted dictionary: {'is': [10], 'gfg': [4, 6]}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using all() + dictionary comprehension
The combination of above functions can be used to solve this problem. This is one-liner solution and uses all() to check for elements membership to decide for filtration. The dictionary comprehension performs task of construction of dictionary.
Python3
# 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
req_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 all(vals in req_list for vals in val)}
# printing result
print("The extracted dictionary: " + str(res))
Output : The original dictionary : {'is': [10], 'best': [4, 5, 7], 'gfg': [4, 6]}
The extracted dictionary: {'is': [10], 'gfg': [4, 6]}
Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #3: Using set intersection + dictionary comprehension
- Define a function named extract_dict that takes two parameters, req_list and test_dict.
- Convert req_list to a set named set_req_list.
- Create a dictionary comprehension that iterates over the items of test_dict and filters out the items whose value set is not a subset of set_req_list.
- Return the resulting dictionary.
- Call the extract_dict function with req_list and test_dict as arguments.
- Print the original dictionary and the extracted dictionary.
Python3
# Python3 code to demonstrate working of
# Extract dictionary items with List elements
# Using set intersection + dictionary comprehension
# Define function to extract dictionary items
def extract_dict(req_list, test_dict):
set_req_list = set(req_list)
return {k:v for k,v in test_dict.items() if set(v).issubset(set_req_list)}
# initialize dictionary
test_dict = {'gfg' : [4, 6], 'is' : [10], 'best' : [4, 5, 7]}
# print original dictionary
print("The original dictionary: " + str(test_dict))
# initialize required list
req_list = [4, 6, 10]
# extract dictionary items with list elements
res = extract_dict(req_list, test_dict)
# print extracted dictionary
print("The extracted dictionary: " + str(res))
OutputThe original dictionary: {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
The extracted dictionary: {'gfg': [4, 6], 'is': [10]}
Time complexity: O(n*m), where n is the number of items in test_dict and m is the maximum length of the value list in test_dict. This is because we iterate over the items of test_dict and then over the items of the value list.
Auxiliary space: O(k), where k is the number of items in the resulting dictionary. We store the resulting dictionary in memory.
Method 4: Using for loop and conditional statements
- We define a helper function called extract_dict_items that takes two arguments req_list and test_dict.
- We initialize an empty dictionary called result_dict to store the key-value pairs that meet our condition.
- We iterate through the key-value pairs of the dictionary using a for loop.
- For each key-value pair, we check if all the items in the value list are also in the req_list using the all() function and a conditional statement.
- If the condition is True, we add the key-value pair to the result_dict.
- After iterating through all the key-value pairs, we return the result_dict.
- Finally, we call the extract_dict_items() function with the req_list and test_dict arguments, and print the original and extracted dictionaries.
Python3
# helper function
def extract_dict_items(req_list, test_dict):
result_dict = {}
for key, val in test_dict.items():
if all(item in req_list for item in val):
result_dict[key] = val
return result_dict
# 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
req_list = [4, 6, 10]
# Extract dictionary items with List elements using for loop and conditional statements
res = extract_dict_items(req_list, test_dict)
# printing result
print("The extracted dictionary: " + str(res))
OutputThe original dictionary: {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
The extracted dictionary: {'gfg': [4, 6], 'is': [10]}
Time complexity: O(n*m), where n is the number of key-value pairs in the dictionary, and m is the maximum length of the value lists.
Auxiliary space: O(k), where k is the number of key-value pairs that meet the condition.
Method #5: Using filter() and lambda function
In this method, we can use the built-in function filter() along with a lambda function to filter out the dictionary items that meet the criteria. Here's the step-by-step approach:
- Define a lambda function that takes in a key-value pair of the dictionary and returns True if all the values in the list associated with the key are present in the req_list, else False.
- Use the filter() function to filter out the key-value pairs that meet the criteria defined in the lambda function.
- Convert the filtered items into a dictionary using the dict() function.
Python3
# 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
req_list = [4, 6, 10]
# define the lambda function
is_subset = lambda key_val: all(val in req_list for val in key_val[1])
# use the filter function to filter out the key-value pairs that meet the criteria
filtered_items = filter(is_subset, test_dict.items())
# convert the filtered items into a dictionary
res = dict(filtered_items)
# printing result
print("The extracted dictionary: " + str(res))
OutputThe original dictionary: {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
The extracted dictionary: {'gfg': [4, 6], 'is': [10]}
Time Complexity: The time complexity of this approach depends on the size of the dictionary and the length of the req_list.
Auxiliary Space: The space complexity of this approach is O(n), where n is the number of items in the dictionary.
Method 6 : using list comprehension
Step-by-step approach:
- Define the original dictionary test_dict with keys and values.
- Print the original dictionary using print().
- Define req_list as the required list of values.
- Create an empty dictionary result_dict.
- Use a for loop to iterate through the items in test_dict using .items().
- Check if all the values of the current item are in req_list using all().
- If all values are in req_list, add the key-value pair to result_dict.
- Print the extracted dictionary using print().
Python3
test_dict = {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
print("The original dictionary: " + str(test_dict))
req_list = [4, 6, 10]
result_dict = {}
for key, values in test_dict.items():
if all(val in req_list for val in values):
result_dict[key] = values
print("The extracted dictionary: " + str(result_dict))
OutputThe original dictionary: {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
The extracted dictionary: {'gfg': [4, 6], 'is': [10]}
The time complexity of this code is O(N*M), where N is the number of keys in the dictionary and M is the maximum length of the lists in the dictionary.
The auxiliary space complexity of this code is O(N), where N is the number of keys in the dictionary.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read