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
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)}
test_dict = {'gfg' : [4, 6], 'is' : [10], 'best' : [4, 5, 7]}
print("The original dictionary : " + str(test_dict))
req_list = [4, 6, 10]
res = hlper_fnc(req_list, test_dict)
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
test_dict = {'gfg' : [4, 6], 'is' : [10], 'best' : [4, 5, 7]}
print("The original dictionary : " + str(test_dict))
req_list = [4, 6, 10]
res = {key: val for key, val in test_dict.items() if all(vals in req_list for vals in val)}
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
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)}
test_dict = {'gfg' : [4, 6], 'is' : [10], 'best' : [4, 5, 7]}
print("The original dictionary: " + str(test_dict))
req_list = [4, 6, 10]
res = extract_dict(req_list, test_dict)
print("The extracted dictionary: " + str(res))
|
Output
The 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
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
test_dict = {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
print("The original dictionary: " + str(test_dict))
req_list = [4, 6, 10]
res = extract_dict_items(req_list, test_dict)
print("The extracted dictionary: " + str(res))
|
Output
The 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
test_dict = {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
print("The original dictionary: " + str(test_dict))
req_list = [4, 6, 10]
is_subset = lambda key_val: all(val in req_list for val in key_val[1])
filtered_items = filter(is_subset, test_dict.items())
res = dict(filtered_items)
print("The extracted dictionary: " + str(res))
|
Output
The 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))
|
Output
The 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
jQWidgets jqxKanban rtl Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxKanban is used for representing the kanban method for a project. The rtl property is used for setting or get
2 min read
Angular 10 I18nPluralPipe API
In this article, we are going to see what is I18nPluralPipe in Angular 10 and how to use it. The I18nPluralPipe is a map that takes a string value that pluralizes according to given rules. Syntax: {{ value | i18nPlural : map [ : rule]}} NgModule: Module used by I18nPluralPipe is: CommonModule Approa
2 min read
Angular 10 I18nSelectPipe API
In this article, we are going to see what is I18nSelectPipe in Angular 10 and how to use it. I18nSelectPipe is a selector that is used to displays the string that matches the current value. Syntax: {{ value | i18nSelect : map}} NgModule: Module used by I18nSelectPipe is: CommonModule Approach: Creat
2 min read
jQWidgets jqxKanban templateContent Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxKanban is used for representing the kanban method for a project. The templateContent property is used for se
2 min read
Angular10 percentPipe
In this article, we are going to see what is percentPipe in Angular 10 and how to use it. The percentPipe is used to Transform a number to a percentage string. Syntax: {{ value | percent [ : digitsInfo [ : locale ] ] }} NgModule: Module used by percentPipe is: CommonModule Approach: Create the angul
2 min read
jQWidgets jqxKanban resources Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxKanban is used for representing the kanban method for a project. The resources property is used for setting
2 min read
Create a User Blocking project using HTML CSS & JavaScript
The User Blocking project is a simple application that allows users to block or unblock certain users. It provides a basic interface to add users to a block list and remove them from the list. In this article, we are going to implement the functionality that can block a user by clicking a button and
4 min read
jQWidgets jqxKanban template Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxKanban is used for representing the kanban method for a project. The template property is used for setting o
2 min read
jQWidgets jqxKanban theme Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxKanban is used for representing the kanban method for a project. The theme property is used for setting or g
2 min read
Angular PrimeNG BlockUI Verification
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see how to use the BlockUI component Verification in Angular PrimeNG. The B
3 min read
jQWidgets jqxDropDownList rtl Property
Introduction: jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxDropDownList widget is a jQuery drop-down list that contains a list of selectable items displa
2 min read
jQWidgets jqxListMenu rtl Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxListMenu is a jQuery widget that is used to display a collection of Ordered and Unordered Lists. We can crea
2 min read
jQWidgets jqxKanban ready Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxKanban is used for representing the kanban method for a project. The ready property is used for setting or g
2 min read
Angular PrimeNG Styling of AvatarGroup
Angular PrimeNG is an open-source front-end UI library that has many native Angular UI components which help developers to build a fast and scalable web solution. In this article, we will be seeing Angular PrimeNG Styling of AvatarGroup. The AvatarGroup Component is used to group avatars together. T
3 min read
Angular PrimeNG Form Calendar Multiple Months Component
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see how to use the Calendar Form with the Multiple Months component in Angu
3 min read
Angular PrimeNG AvatarGroup
Angular PrimeNG is a UI component library for Angular Applications. It offers many pre-built themes and UI components for a variety of tasks like inputs, menus, charts, Buttons, etc. In this article, we will be seeing Angular PrimeNG AvatarGroup. The AvatarGroup Component is used to group avatars to
2 min read
Angular PrimeNG Timeline Opposite
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. This article will show us how to use the Timeline Opposite in Angular PrimeNG. We will also learn ab
3 min read
Angular PrimeNG Form Chips Templates
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. This article will show us how to use Angular PrimeNG Form Chips Templates Component. The Chips compo
3 min read
Angular PrimeNG BlockUI Document
Angular PrimeNG is a front-end UI toolkit for Angular applications. It has a wide variety of angular components that helps developers to build web applications in less time as they don't have to make everything from scratch. In this article, we will discuss BlockUI Document in Angular PrimeNG. The B
3 min read