Python – Filter key’s value from other key
Last Updated :
16 May, 2023
Sometimes, while working with Python dictionary, we can have a problem in which we need to extract a value from dictionary list of the key on basis of some other key equality. This kind of problem is common in domains that include data, for e.g web development. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [{‘gfg’ : 5, ‘is’ : 8, ‘best’ : 24}, {‘gfg’ : 7, ‘is’ : 12, ‘best’ : 24}] req_key = ‘gfg’ [ Requested Key ] fil_key = ‘best’ [ Filtering Key ] fil_val = 24 [ Filtering value to be checked ]
Output : [5, 7]
Input : test_list = [{‘gfg’ : 5, ‘is’ : 8, ‘best’ : 24}] req_key = ‘gfg’ [ Requested Key ] fil_key = ‘best’ [ Filtering Key ] fil_val = 24 [ Filtering value to be checked ]
Output : [5]
Method #1: Using loop This is brute force way to solve this problem. In this, we manually iterate the entire list and check for filter key’s value, on equality we extract the required key’s value.
Python3
test_list = [{ 'gfg' : 5 , 'is' : 8 , 'best' : 12 },
{ 'gfg' : 7 , 'is' : 12 , 'best' : 24 },
{ 'gfg' : 20 , 'is' : 17 , 'best' : 18 }]
print ( "The original list is : " + str (test_list))
req_key = 'gfg'
fil_key = 'best'
fil_val = 24
res = []
for sub in test_list:
if sub[fil_key] = = fil_val:
res.append(sub[req_key])
print ( "The required value : " + str (res))
|
Output
The original list is : [{'gfg': 5, 'is': 8, 'best': 12}, {'gfg': 7, 'is': 12, 'best': 24}, {'gfg': 20, 'is': 17, 'best': 18}]
The required value : [7]
Time complexity: O(n), where n is the number of dictionaries in the list test_list. This is because the program loops through each dictionary in the list exactly once.
Auxiliary space: O(1), as the program only creates a few variables to store the input and output values, and the space requirements for these variables do not increase with the size of the input. The only variable created with a size proportional to the input is the list res, but its size is bounded by the number of matching values found, which is at most the number of dictionaries in the input list.
Method #2: Using list comprehension This is yet another way to solve this problem. In this, we perform the task similar in above method, in a shorthand way using list comprehension construct.
Python3
test_list = [{ 'gfg' : 5 , 'is' : 8 , 'best' : 12 },
{ 'gfg' : 7 , 'is' : 12 , 'best' : 24 },
{ 'gfg' : 20 , 'is' : 17 , 'best' : 18 }]
print ( "The original list is : " + str (test_list))
req_key = 'gfg'
fil_key = 'best'
fil_val = 24
res = [sub[req_key] for sub in test_list if sub[fil_key] = = fil_val]
print ( "The required value : " + str (res))
|
Output
The original list is : [{'gfg': 5, 'is': 8, 'best': 12}, {'gfg': 7, 'is': 12, 'best': 24}, {'gfg': 20, 'is': 17, 'best': 18}]
The required value : [7]
Method 3: Using the filter() function and lambda function:
Python3
test_list = [{ 'gfg' : 5 , 'is' : 8 , 'best' : 12 },
{ 'gfg' : 7 , 'is' : 12 , 'best' : 24 },
{ 'gfg' : 20 , 'is' : 17 , 'best' : 18 }]
req_key = 'gfg'
fil_key = 'best'
fil_val = 24
res = list ( filter ( lambda x: x[fil_key] = = fil_val, test_list))
res = [d[req_key] for d in res]
print ( "The required value : " + str (res))
|
Output
The required value : [7]
Method #4: Using list comprehension with conditional
- Initialize the list comprehension by enclosing it in square brackets.
- Use the for loop to iterate over each sub-dictionary in the test_list.
- Use a conditional statement to check if the value of the fil_key in the current sub-dictionary is equal to fil_val.
- If the condition is true, append the value of the req_key to the list.
- Print the resulting list.
Python3
test_list = [{ 'gfg' : 5 , 'is' : 8 , 'best' : 12 },
{ 'gfg' : 7 , 'is' : 12 , 'best' : 24 },
{ 'gfg' : 20 , 'is' : 17 , 'best' : 18 }]
print ( "The original list is : " + str (test_list))
req_key = 'gfg'
fil_key = 'best'
fil_val = 24
res = [sub[req_key] for sub in test_list if sub[fil_key] = = fil_val]
print ( "The required value : " + str (res))
|
Output
The original list is : [{'gfg': 5, 'is': 8, 'best': 12}, {'gfg': 7, 'is': 12, 'best': 24}, {'gfg': 20, 'is': 17, 'best': 18}]
The required value : [7]
Time Complexity: O(n), where n is the number of sub-dictionaries in the test_list.
Auxiliary Space: O(k), where k is the number of sub-dictionaries in the res list.
Method #6: Using map(), filter(), and lambda function
- Use the map() function with a lambda function to extract the values of the ‘gfg’ key from each dictionary in the list. The lambda function takes a dictionary as input and returns the value of the ‘gfg’ key.
- Use the filter() function with a lambda function to select the dictionaries that have a value of 24 for the ‘best’ key. The lambda function takes a dictionary as input and returns True if the value of the ‘best’ key is 24.
- Use the list() function to convert the map object returned by the map() function to a list.
- Print the list of values of the ‘gfg’ key from the filtered dictionaries.
Python3
test_list = [{ 'gfg' : 5 , 'is' : 8 , 'best' : 12 },
{ 'gfg' : 7 , 'is' : 12 , 'best' : 24 },
{ 'gfg' : 20 , 'is' : 17 , 'best' : 18 }]
req_key = 'gfg'
fil_key = 'best'
fil_val = 24
res = list ( map ( lambda x: x[req_key], filter ( lambda x: x[fil_key] = = fil_val, test_list)))
print ( "The required value : " + str (res))
|
Output
The required value : [7]
Time complexity: O(n), where n is the number of dictionaries in the list,
Auxiliary space: O(n) for the filtered list.
Method # 7: Using a generator expression with multiple conditions
- Use a generator expression to iterate over the list of dictionaries test_list.
- For each dictionary d in test_list, use the following condition:
- This condition checks if the dictionary has a key called req_key and the value of the key fil_key is equal to fil_val.
- If the condition is true, yield the value of the key req_key in the dictionary.
- Use the list() function to convert the generator expression to a list and store it in the variable res.
- Print the result.
Python3
test_list = [{ 'gfg' : 5 , 'is' : 8 , 'best' : 12 },
{ 'gfg' : 7 , 'is' : 12 , 'best' : 24 },
{ 'gfg' : 20 , 'is' : 17 , 'best' : 18 }]
req_key = 'gfg'
fil_key = 'best'
fil_val = 24
res = list (d[req_key] for d in test_list if d.get(req_key) and d.get(fil_key) = = fil_val)
print ( "The required value : " + str (res))
|
Output
The required value : [7]
Time complexity: O(n), where n is the number of dictionaries in test_list.
Auxiliary space: O(k), where k is the number of dictionaries that satisfy the conditions.
Similar Reads
Python - Extract target key from other key values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract particular key on basis of other matching record keys when there is exact match. Lets discuss certain ways in which this task can be performed. Method #1: Using loop + conditions This is one of the w
11 min read
Python - Filter Key from Nested item
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract the keys which have a particular key-value pair as part of their nested item. This kind of problem is common in web development domain. Lets discuss certain ways in which this task can be performed.
8 min read
Python - Remove K valued key from Nested Dictionary
We are given a nested dictionary we need to remove K valued key. For example, we are given a nested dictionary d = { "a": 1, "b": {"c": 2,"d": {"e": 3,"f": 1},"g": 1},"h": [1, {"i": 1, "j": 4}]} we need to remove K valued key ( in our case we took k value as 1 ) from it so that the output should be
3 min read
Python | Search Key from Value
The problem of finding a value from a given key is quite common. But we may have a problem in which we wish to get the back key from the input key we feed. Let's discuss certain ways in which this problem can be solved. Method #1 : Using Naive Method In this method, we just run a loop for each of th
4 min read
Remove Kth Key from Dictionary - Python
We are given a dictionary we need to remove Kth key from the dictionary. For example, we are given a dictionary d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'} we need to remove the key2 so that the output should be {'key1': 'value1', 'key3': 'value3', 'key4': 'value4'}.
3 min read
Python - Tuple key detection from value list
Sometimes, while working with record data, we can have a problem in which we need to extract the key which has matching value of K from its value list. This kind of problem can occur in domains that are linked to data. Lets discuss certain ways in which this task can be performed. Method #1 : Using
6 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
Get List of Values From Dictionary - Python
We are given a dictionary and our task is to extract all the values from it and store them in a list. For example, if the dictionary is d = {'a': 1, 'b': 2, 'c': 3}, then the output would be [1, 2, 3]. Using dict.values()We can use dict.values() along with the list() function to get the list. Here,
2 min read
Python | Sum values for each key in nested dictionary
Given a nested dictionary and we have to find sum of particular value in that nested dictionary. This is basically useful in cases where we are given a JSON object or we have scraped a particular page and we want to sum the value of a particular attribute in objects. Code #1: Find sum of sharpness v
2 min read
Python - Sort Nested keys by Value
Sometimes, while working with data records, we can have a problem in which we need to perform the sorting of nested keys of dictionary by the value of occurrence. This can have applications in arranging scores, prices etc. Lets discuss a way in which this task can be performed. Method #1 : Using sor
3 min read