Open In App

Python – Extract values of Particular Key in Nested Values

Last Updated : 28 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a dictionary with nested dictionaries as values, extract all the values with of particular key.

Input : test_dict = {‘Gfg’ : {“a” : 7, “b” : 9, “c” : 12}, ‘is’ : {“a” : 15, “b” : 19, “c” : 20}, ‘best’ :{“a” : 5, “b” : 10, “c” : 2}}, temp = “b” 
Output : [9, 10, 19] 
Explanation : All values of “b” key are extracted. 

Input : test_dict = {‘Gfg’ : {“a” : 7, “b” : 9, “c” : 12}, ‘is’ : {“a” : 15, “b” : 19, “c” : 20}, ‘best’ :{“a” : 5, “b” : 10, “c” : 2}}, temp = “a” 
Output : [7, 15, 5] 
Eplanation : All values of “a” key are extracted.

Method #1 : Using list comprehension + items()

This is one of the ways in which this task can be performed. In this, we use list comprehension to perform the task of extracting particular key and items() is used to get all the items().

Python3




# Python3 code to demonstrate working of
# Extract values of Particular Key in Nested Values
# Using list comprehension
 
# initializing dictionary
test_dict = {'Gfg' : {"a" : 7, "b" : 9, "c" : 12},
             'is' : {"a" : 15, "b" : 19, "c" : 20},
             'best' :{"a" : 5, "b" : 10, "c" : 2}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing key
temp = "c"
 
# using item() to extract key value pair as whole
res = [val[temp] for key, val in test_dict.items() if temp in val]
 
# printing result
print("The extracted values : " + str(res))


Output

The original dictionary is : {'Gfg': {'a': 7, 'b': 9, 'c': 12}, 'is': {'a': 15, 'b': 19, 'c': 20}, 'best': {'a': 5, 'b': 10, 'c': 2}}
The extracted values : [12, 20, 2]

Time Complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary Space: O(m), where m is the number of values that have the key we are looking for.

Method #2 : Using list comprehension + values() + keys() 

The combination of above functions can be used to solve this problem. In this, we use values() and keys() to get values and keys separately rather than at once extracted using items().

Python3




# Python3 code to demonstrate working of
# Extract values of Particular Key in Nested Values
# Using list comprehension + values() + keys()
 
# initializing dictionary
test_dict = {'Gfg' : {"a" : 7, "b" : 9, "c" : 12},
             'is' : {"a" : 15, "b" : 19, "c" : 20},
             'best' :{"a" : 5, "b" : 10, "c" : 2}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing key
temp = "c"
 
# using keys() and values() to extract values
res = [sub[temp] for sub in test_dict.values() if temp in sub.keys()]
 
# printing result
print("The extracted values : " + str(res))


Output

The original dictionary is : {'Gfg': {'a': 7, 'b': 9, 'c': 12}, 'is': {'a': 15, 'b': 19, 'c': 20}, 'best': {'a': 5, 'b': 10, 'c': 2}}
The extracted values : [12, 20, 2]

Time complexity: O(n), where n is the number of values in the dictionary.
Auxiliary space: O(m), where m is the number of values that contain the key ‘c’.

Method 3 : using a for loop and if condition.

 Here are the steps:

  1. Initialize an empty list to store the values of the particular key.
  2. Iterate over each value in the dictionary using a for loop.
  3. Check if the particular key exists in the current value using an if condition.
  4. If the key exists, append its value to the list initialized in step 1.
  5. Print the list containing the extracted values.

Python3




# initializing dictionary
test_dict = {'Gfg': {'a': 7, 'b': 9, 'c': 12},
             'is': {'a': 15, 'b': 19, 'c': 20},
             'best': {'a': 5, 'b': 10, 'c': 2}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing key
temp = "c"
 
# initializing empty list
res = []
 
# iterating over each value in dictionary
for value in test_dict.values():
     
    # checking if key exists in current value
    if temp in value:
         
        # appending value of key to the result list
        res.append(value[temp])
 
# printing result
print("The extracted values : " + str(res))


Output

The original dictionary is : {'Gfg': {'a': 7, 'b': 9, 'c': 12}, 'is': {'a': 15, 'b': 19, 'c': 20}, 'best': {'a': 5, 'b': 10, 'c': 2}}
The extracted values : [12, 20, 2]

Time Complexity: O(n*m), where n is the number of values in the dictionary and m is the maximum number of keys in a value.

Auxiliary Space: O(k), where k is the number of values in the list ‘res’ containing the extracted values. 



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 ways in which this task can be performed. In this,
11 min read
Python | Get values of particular key in list of dictionaries
Sometimes, we may require a way in which we have to get all the values of the specific key from a list of dictionaries. This kind of problem has a lot of applications in the web development domain in which we sometimes have a JSON and require just to get a single column from records. Let's discuss certain ways in which this problem can be solved. M
10 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. Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" Output : 5 Explanation : "Gfg" is present in list and has value 5 in dictionary. Input : test_list = ["G
11 min read
Python - Get particular Nested level Items from Dictionary
Given a dictionary, extract items from a particular level. Examples: Input : {"Gfg" : { "n1": 3, "nd2": { "n2" : 6 }}, "is" : { "ne1": 5, "ndi2": { "ne2" : 8, "ne22" : 10 } }}, K = 2 Output : {'n2': 6, 'ne2': 8, 'ne22': 10} Explanation : 2nd nesting items are extracted. Input : {"Gfg" : { "n1": 3, "nd2": { "n2" : 6 }}, "is" : { "ne1": 5, "ndi2": {
4 min read
Python - Extract selective keys' values Including Nested Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys' values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys' values. Let's discuss certain w
7 min read
Python - Extract Particular data type rows
Given A Matrix, extract all the rows which have all the elements with particular data type. Input : test_list = [[4, 5, "Hello"], [2, 6, 7], ["g", "f", "g"], [9, 10, 11]], data_type = int Output : [[2, 6, 7], [9, 10, 11]] Explanation : All lists with integer are extracted. Input : test_list = [[4, 5, "Hello"], [2, 6, 7], ["g", "f", "g"], [9, 10, 11
3 min read
How to extract a particular column from 1D array of tuples?
In this article, we will cover how to extract a particular column from a 1-D array of tuples in python. Example Input: [(18.18,2.27,3.23),(36.43,34.24,6.6),(5.25,6.16,7.7),(7.37,28.8,8.9)] Output: [3.23, 6.6 , 7.7 , 8.9 ] Explanation: Extracting the 3rd column from 1D array of tuples. Method 1: Using Slice As a first step let us first define a 1D a
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 values using sum() function Step-by-step approach:
2 min read
Group List of Dictionary Data by Particular Key in Python
Group List of Dictionary Data by Particular Key in Python can be done using itertools.groupby() method. Itertools.groupby() This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items. Syntax: itertools.groupby(iterable, key_func) Parameters: iterable: Iterable can be of any kind (list, tuple,
3 min read
Python - Check if particular value is present corresponding to K key
Given a list of dictionaries, check whether particular key-value pair exists or not. Input : [{"Gfg" : "4", "is" : "good", "best" : "1"}, {"Gfg" : "9", "is" : "CS", "best" : "10"}], K = "Gfg", val = "find" Output : False Explanation : No value of "Gfg" is "find". Input : [{"Gfg" : "4", "is" : "good", "best" : "1"}, {"Gfg" : "9", "is" : "CS", "best"
3 min read