Python program to extract key-value pairs with substring in a dictionary
Last Updated :
19 Apr, 2023
Given a dictionary list, extract all the dictionaries which have substring present in particular key.
Input : [{“Gfg” : “4”, “best” : “1”}, {“Gfg” : “good CS content”, “best” : “10”}], K = “Gfg”, sub_str = “CS”
Output : [{‘Gfg’: ‘good CS content’, ‘best’: ’10’}]
Explanation : “Gfg” has “CS” as substring value.
Input : [{“Gfg” : “4”, “best” : “1”}, {“Gfg” : “good content”, “best” : “10”}], K = “Gfg”, sub_str = “CS”
Output : []
Explanation : No dictionary with “CS” as substring to “Gfg” key.
Method #1 : Using list comprehension
This is one of the ways in which this task can be performed. In this, we iterate for all the dictionaries and check for key’s value substring presence using in operator.
Python3
test_list = [{ "Gfg" : "4" , "best" : "1" },
{ "Gfg" : "good for CS" , "best" : "8" },
{ "Gfg" : "good CS content" , "best" : "10" }]
print ( "The original list : " + str (test_list))
K = "Gfg"
sub_str = "CS"
res = [val for val in test_list if sub_str in val[K]]
print ( "Dictionaries with particular substring values : " + str (res))
|
Output
The original list : [{'Gfg': '4', 'best': '1'}, {'Gfg': 'good for CS', 'best': '8'}, {'Gfg': 'good CS content', 'best': '10'}]
Dictionaries with particular substring values : [{'Gfg': 'good for CS', 'best': '8'}, {'Gfg': 'good CS content', 'best': '10'}]
Output:
The original list : [{‘Gfg’: ‘4’, ‘best’: ‘1’}, {‘Gfg’: ‘good for CS’, ‘best’: ‘8’}, {‘Gfg’: ‘good CS content’, ‘best’: ’10’}] Dictionaries with particular substring values : [{‘Gfg’: ‘good for CS’, ‘best’: ‘8’}, {‘Gfg’: ‘good CS content’, ‘best’: ’10’}]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using map() + in operator
This is yet another way in which this task can be performed. In this, we extract all the values with required substring using map() + lambda function. The in operator is used to check for substring inside the key’s value.
Python3
test_list = [{ "Gfg" : "4" , "best" : "1" },
{ "Gfg" : "good for CS" , "best" : "8" },
{ "Gfg" : "good CS content" , "best" : "10" }]
print ( "The original list : " + str (test_list))
K = "Gfg"
val = "CS"
res = list ( map ( lambda sub: val in sub[K], test_list))
res = [test_list[idx] for idx, ele in enumerate (res) if res[idx]]
print ( "Dictionaries with particular substring values : " + str (res))
|
Output
The original list : [{'Gfg': '4', 'best': '1'}, {'Gfg': 'good for CS', 'best': '8'}, {'Gfg': 'good CS content', 'best': '10'}]
Dictionaries with particular substring values : [{'Gfg': 'good for CS', 'best': '8'}, {'Gfg': 'good CS content', 'best': '10'}]
Output:
The original list : [{‘Gfg’: ‘4’, ‘best’: ‘1’}, {‘Gfg’: ‘good for CS’, ‘best’: ‘8’}, {‘Gfg’: ‘good CS content’, ‘best’: ’10’}] Dictionaries with particular substring values : [{‘Gfg’: ‘good for CS’, ‘best’: ‘8’}, {‘Gfg’: ‘good CS content’, ‘best’: ’10’}]
Method #3: Using a for loop
Use a for loop to iterate over the list of dictionaries, and a conditional statement to check if the substring exists in the value of the “K” key.
Python3
test_list = [{ "Gfg" : "4" , "best" : "1" },
{ "Gfg" : "good for CS" , "best" : "8" },
{ "Gfg" : "good CS content" , "best" : "10" }]
print ( "The original list : " + str (test_list))
K = "Gfg"
sub_str = "CS"
res = []
for d in test_list:
if sub_str in d[K]:
res.append(d)
print ( "Dictionaries with particular substring values : " + str (res))
|
Output
The original list : [{'Gfg': '4', 'best': '1'}, {'Gfg': 'good for CS', 'best': '8'}, {'Gfg': 'good CS content', 'best': '10'}]
Dictionaries with particular substring values : [{'Gfg': 'good for CS', 'best': '8'}, {'Gfg': 'good CS content', 'best': '10'}]
Time Complexity: O(n*k) where n is the number of dictionaries in the list and k is the length of the value of the “K” key in each dictionary.
Auxiliary Space: O(m) where m is the number of dictionaries that contain the substring in the value of the “K” key. The space used by the result list.
Method #4: Using filter() function
step-by-step approach for the code:
- We start by initializing a list of dictionaries called test_list, which contains key-value pairs.
- We print the original list to the console using the print() function.
- We initialize a string variable K to “Gfg”, which is the key we want to search in the dictionaries.
- We initialize a string variable sub_str to “CS”, which is the substring we want to search for in the values associated with the key K.
- We apply the filter() function on the test_list using a lambda function that takes a dictionary x and checks if the substring sub_str exists in the value associated with the key K. If the condition is true, the lambda function returns True, and x is included in the filtered output. Otherwise, False is returned, and x is excluded from the output.
- We convert the filter object to a list using the list() function and store the output in a variable called res.
- Finally, we print the dictionaries in res that have the substring in the value associated with the key K.
Python3
test_list = [{ "Gfg" : "4" , "best" : "1" },
{ "Gfg" : "good for CS" , "best" : "8" },
{ "Gfg" : "good CS content" , "best" : "10" }]
print ( "The original list : " + str (test_list))
K = "Gfg"
sub_str = "CS"
res = list ( filter ( lambda x: sub_str in x[K], test_list))
print ( "Dictionaries with particular substring values : " + str (res))
|
Output
The original list : [{'Gfg': '4', 'best': '1'}, {'Gfg': 'good for CS', 'best': '8'}, {'Gfg': 'good CS content', 'best': '10'}]
Dictionaries with particular substring values : [{'Gfg': 'good for CS', 'best': '8'}, {'Gfg': 'good CS content', 'best': '10'}]
Time complexity: O(n), where n is the number of dictionaries in the input list.
Auxiliary space: O(1), as we are only using a constant amount of space to store the key and target substring.
Method #5 : Using find() method
Approach
- Initiate a for loop to traverse over list of dictionaries, initialise an empty list res
- Check if K key’s value has sub_str in it using find() method , if yes append the dictionary to output list res
- Display res
Python3
test_list = [{ "Gfg" : "4" , "best" : "1" },
{ "Gfg" : "good for CS" , "best" : "8" },
{ "Gfg" : "good CS content" , "best" : "10" }]
print ( "The original list : " + str (test_list))
K = "Gfg"
sub_str = "CS"
res = []
for i in test_list:
if i[K].find(sub_str)! = - 1 :
res.append(i)
print ( "Dictionaries with particular substring values : " + str (res))
|
Output
The original list : [{'Gfg': '4', 'best': '1'}, {'Gfg': 'good for CS', 'best': '8'}, {'Gfg': 'good CS content', 'best': '10'}]
Dictionaries with particular substring values : [{'Gfg': 'good for CS', 'best': '8'}, {'Gfg': 'good CS content', 'best': '10'}]
Time Complexity: O(n*k) where n is the number of dictionaries in the list and k is the length of the value of the “K” key in each dictionary.
Auxiliary Space: O(m) where m is the number of dictionaries that contain the substring in the value of the “K” key. The space used by the result list.
Similar Reads
Python - Extract dictionaries with Empty String value in K key
Given a List of dictionaries, extract all the dictionaries which have empty strings as values of a particular key. Input : test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"}, {"Gfg" : "9", "is" : "CS", "best" : "10"}], K = "Gfg" Output : [] Explanation : No "Gfg" key is empty. Input : test_list
8 min read
Extract Subset of Key-Value Pairs from Python Dictionary
In this article, we will study different approaches by which we can Extract the Subset Of Key-Value Pairs From the Python Dictionary. When we work with Python dictionaries, it often involves extracting subsets of key-value pairs based on specific criteria. This can be useful for tasks such as filter
4 min read
Python - Extract Key's Value, if Key Present in List and Dictionary
Given a list, dictionary and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. For example: a = ["Gfg", "is", "Good", "for", "Geeks"], d = {"Gfg": 5, "Best": 6} and K = "Gfg" then the output will be 5 as "Gfg" is present in both the list an
3 min read
Add a key value pair to Dictionary in Python
The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key. For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'f
3 min read
Python - Extract ith Key's Value of K's Maximum value dictionary
Given Dictionary List, extract i'th keys value depending upon Kth key's maximum value. Input : test_list = [{"Gfg" : 3, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}, {"Gfg" : 9, "is" : 16, "best" : 1}], K = "best", i = "is" Output : 11 Explanation : best is max at 19, its correspondin
9 min read
Python | Extract key-value of dictionary in variables
Sometimes, while working with dictionaries, we can face a problem in which we may have just a singleton dictionary, i.e dictionary with just a single key-value pair, and require to get the pair in separate variables. This kind of problem can come in day-day programming. Let's discuss certain ways in
5 min read
Python program to extract the Unique Dictionary Value List elements
Given Dictionary with value lists, extract all unique values. Input : test_dict = {"Gfg" : [6, 7, 4, 6], "Geeks" : [6, 8, 5, 2]} Output : [6, 7, 4, 8, 5, 2] Explanation : All distincts elements extracted. Input : test_dict = {"Gfg" : [6, 7, 6], "Geeks" : [6, 8, 5, 2]} Output : [6, 7, 8, 5, 2] Explan
6 min read
Python program to print the dictionary in table format
Given a Dictionary. The task is to print the dictionary in table format. Examples: Input: {1: ["Samuel", 21, 'Data Structures'], 2: ["Richie", 20, 'Machine Learning'], 3: ["Lauren", 21, 'OOPS with java'], }Output: NAME AGE COURSE Samuel 21 Data Structures Richie 20 Machine Learning Lauren 21 OOPS wi
2 min read
Filter Dictionary Key based on the Values in Selective List - Python
We are given a dictionary where each key is associated with a value and our task is to filter the dictionary based on a selective list of values. We want to retain only those key-value pairs where the value is present in the list. For example, we have the following dictionary and list: d = {'apple':
3 min read
Ways to extract all dictionary values | Python
While working with Python dictionaries, there can be cases in which we are just concerned about getting the values list and don't care about keys. This is yet another essential utility and solution to it should be known and discussed. Let's perform this task through certain methods. Method #1 : Usin
3 min read