Python – Filter Key from Nested item
Last Updated :
27 Apr, 2023
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.
Input : test_dict = {‘gfg’ : {‘best’ : 10, ‘good’ : 5}}
Output : [‘gfg’]
Input : test_dict = {‘gfg’ : {‘best’ : 10, ‘good’ : 12}}
Output : []
Method #1: Using loop + __contains__ The combination of above functions constitutes the brute force way to perform this task. In this, we iterate for each key using loop and check for value presence using __contains__.
Python3
test_dict = { 'gfg' : { 'best' : 4 , 'good' : 5 },
'is' : { 'better' : 6 , 'educational' : 4 },
'CS' : { 'priceless' : 6 },
'Maths' : { 'good' : 5 }}
print ( "The original dictionary : " + str (test_dict))
que_dict = { 'good' : 5 }
res = []
for key, val in test_dict.items():
if (test_dict[key].__contains__( 'good' )):
if (test_dict[key][ 'good' ] = = que_dict[ 'good' ]):
res.append(key)
print ( "Match keys : " + str (res))
|
Output
The original dictionary : {'gfg': {'best': 4, 'good': 5}, 'is': {'better': 6, 'educational': 4}, 'CS': {'priceless': 6}, 'Maths': {'good': 5}}
Match keys : ['gfg', 'Maths']
Time complexity: O(N*M), where N is the number of items in the test_dict and M is the number of keys in the que_dict.
Auxiliary Space: O(K), where K is the number of matched keys. This is because we are storing the matched keys in the res list.
Method #2: Using dictionary comprehension + get() The combination of above functions provide another way to solve this problem. In this, we perform the check of element presence using get().
Python3
test_dict = { 'gfg' : { 'best' : 4 , 'good' : 5 },
'is' : { 'better' : 6 , 'educational' : 4 },
'CS' : { 'priceless' : 6 },
'Maths' : { 'good' : 5 }}
print ( "The original dictionary : " + str (test_dict))
que_dict = { 'good' : 5 }
res = [ idx for idx in test_dict if test_dict[idx].get( 'good' ) = = que_dict[ 'good' ] ]
print ( "Match keys : " + str (res))
|
Output
The original dictionary : {'gfg': {'best': 4, 'good': 5}, 'is': {'better': 6, 'educational': 4}, 'CS': {'priceless': 6}, 'Maths': {'good': 5}}
Match keys : ['gfg', 'Maths']
Time complexity: O(N*M), where N is the number of items in the test_dict and M is the number of keys in the que_dict.
Auxiliary Space: O(K), where K is the number of matched keys. This is because we are storing the matched keys in the res list.
Method 3: Using simple for loop
Python3
test_dict = { 'gfg' : { 'best' : 4 , 'good' : 5 },
'is' : { 'better' : 6 , 'educational' : 4 },
'CS' : { 'priceless' : 6 },
'Maths' : { 'good' : 5 }}
print ( "The original dictionary : " + str (test_dict))
que_dict = { 'good' : 5 }
res = []
for key, value in test_dict.items():
if 'good' in value and value[ 'good' ] = = que_dict[ 'good' ]:
res.append(key)
print ( "Match keys : " + str (res))
|
Output
The original dictionary : {'gfg': {'best': 4, 'good': 5}, 'is': {'better': 6, 'educational': 4}, 'CS': {'priceless': 6}, 'Maths': {'good': 5}}
Match keys : ['gfg', 'Maths']
Time Complexity: O(n), where n is the number of keys in the dictionary.
Auxiliary Space: O(1)
Method #4: Using List Comprehension
This method uses a list comprehension to iterate through the dictionary items and checks if the nested dictionary contains the key “good” with a value of 5, as specified in the que_dict. If so, it appends the outer key to a list comprehension.
Python3
test_dict = { 'gfg' : { 'best' : 4 , 'good' : 5 },
'is' : { 'better' : 6 , 'educational' : 4 },
'CS' : { 'priceless' : 6 },
'Maths' : { 'good' : 5 }}
print ( "The original dictionary : " + str (test_dict))
que_dict = { 'good' : 5 }
res = [key for key, value in test_dict.items() if 'good' in value and value[ 'good' ] = = que_dict[ 'good' ]]
print ( "Match keys : " + str (res))
|
Output
The original dictionary : {'gfg': {'best': 4, 'good': 5}, 'is': {'better': 6, 'educational': 4}, 'CS': {'priceless': 6}, 'Maths': {'good': 5}}
Match keys : ['gfg', 'Maths']
Time complexity: O(n), where n is the number of items in the test_dict. This is because the list comprehension iterates through all the items in test_dict once.
Auxiliary space: O(k), where k is the number of matches found. This is because it creates a list to store the matching keys. In the worst case, where all items in test_dict contain the key “good” with a value of 5, the space complexity would be O(n). However, in most cases, the number of matches would be smaller than the number of items in test_dict.
Method #5: Using the built-in filter() function with a lambda function
This approach uses the filter() function to create a new iterable that only contains the keys that meet the specified conditions. The lambda function checks if the key’s nested item contains the specified key and if its value is equal to the value in the que_dict.
Python3
test_dict = { 'gfg' : { 'best' : 4 , 'good' : 5 },
'is' : { 'better' : 6 , 'educational' : 4 },
'CS' : { 'priceless' : 6 },
'Maths' : { 'good' : 5 }}
print ( "The original dictionary : " + str (test_dict))
que_dict = { 'good' : 5 }
res = list ( filter ( lambda x: 'good' in test_dict[x] and test_dict[x][ 'good' ] = = que_dict[ 'good' ], test_dict))
print ( "Match keys : " + str (res))
|
Output
The original dictionary : {'gfg': {'best': 4, 'good': 5}, 'is': {'better': 6, 'educational': 4}, 'CS': {'priceless': 6}, 'Maths': {'good': 5}}
Match keys : ['gfg', 'Maths']
Time complexity: O(n), where n is the number of items in the dictionary
Auxiliary space: O(k), where k is the number of matching keys.
Method #6: Using recursion
- Initialize the dictionary test_dict with the given key-value pairs.
- Print the original dictionary using the print() function.
- Initialize the dictionary que_dict with the key ‘good’ and the value 5.
- Define a recursive function filter_dict() that takes in a dictionary and a query dictionary and returns a list of keys from the original dictionary that meet the filtering condition.
- In the function, iterate through the items in the dictionary, and if the value is another dictionary, recursively call the function on that nested dictionary.
- If the nested dictionary contains the key ‘good’ and its value is equal to the value in the query dictionary, add the key to the result list.
- Return the result list.
- Call the filter_dict() function with the test_dict and que_dict dictionaries to get the matching keys.
- Print the resulting list of keys using the print() function.
Python3
test_dict = { 'gfg' : { 'best' : 4 , 'good' : 5 },
'is' : { 'better' : 6 , 'educational' : 4 },
'CS' : { 'priceless' : 6 },
'Maths' : { 'good' : 5 }}
print ( "The original dictionary : " + str (test_dict))
que_dict = { 'good' : 5 }
def filter_dict(dict_to_filter, query_dict):
res = []
for key, val in dict_to_filter.items():
if isinstance (val, dict ):
if 'good' in val and val[ 'good' ] = = query_dict[ 'good' ]:
res.append(key)
res + = filter_dict(val, query_dict)
return res
res = filter_dict(test_dict, que_dict)
print ( "Match keys : " + str (res))
|
Output
The original dictionary : {'gfg': {'best': 4, 'good': 5}, 'is': {'better': 6, 'educational': 4}, 'CS': {'priceless': 6}, 'Maths': {'good': 5}}
Match keys : ['gfg', 'Maths']
Time complexity: O(n), where n is the total number of key-value pairs in all the nested dictionaries.
Auxiliary space: O(h), where h is the maximum depth of the nested dictionaries.
Similar Reads
Python - Flatten Nested Keys
Sometimes, while working with Python data, we can have a problem in which we need to perform the flattening of certain keys in nested list records. This kind of problem occurs while data preprocessing. Let us discuss certain ways in which this task can be performed. Method #1: Using loopThis is a br
10 min read
Python - Filter key's value from other key
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 th
7 min read
Count the Key from Nested Dictionary in Python
In Python, counting the occurrences of keys within a nested dictionary often requires traversing through its complex structure. In this article, we will see how to count the key from the nested dictionary in Python. Count the Key from the Nested Dictionary in PythonBelow are some ways and examples b
4 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
Get particular Nested level Items from Dictionary - Python
Our task is to extract all items at a particular depth level from a given nested dictionary,. This means retrieving only the key-value pairs that exist at a specific depth within the dictionary. For example: d = {'a': {'b': {'c': 5, 'd': 6}, 'e': 7}, 'f': 8} and if we want all key-value pairs at lev
2 min read
Remove K Value Items from Dictionary Nesting - Python
We are given a dictionary we need to remove K value items from dictionary. For example we are having a dictionary d = {'a': {'b': 'remove', 'c': 'keep'}, 'd': {'e': 'remove', 'f': 'keep'}} we need to remove the K value suppose in this case K is 'remove' so that output should be {'a': {'c': 'keep'},
3 min read
Python Remove Item from Dictionary by Key
Dictionaries in Python store data as key-value pairs. Often, we need to remove a specific key-value pair to modify or clean the dictionary. For instance, consider the dictionary d = {'a': 1, 'b': 2, 'c': 3}; we might want to remove the key 'b'. Let's explore different methods to achieve this. Using
3 min read
Python - Sorted Nested Keys in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the keys of nested dictionaries and render them in sorted order. This kind of application can occur in domains in which we work with data. Lets discuss certain ways in which this task can be perf
4 min read
Get Next Key in Dictionary - Python
We are given a dictionary and need to find the next key after a given key, this can be useful when iterating over dictionaries or accessing elements in a specific order. For example, consider the dictionary: data = {"a": 1, "b": 2, "c": 3, "d": 4} if the current key is "b" then the next key should b
2 min read
Python - How to Iterate over nested dictionary ?
In this article, we will discuss how to iterate over a nested dictionary in Python. Nested dictionary means dictionary inside a dictionary and we are going to see every possible way of iterating over such a data structure. Nested dictionary in use: {'Student 1': {'Name': 'Bobby', 'Id': 1, 'Age': 20}
3 min read