In this article, we will learn how we can Get all Values from Nested Dictionary in Python Programming. A nested Dictionary in Python is a dictionary that contains another dictionary as its values. Using this, we can create a nested structure where each of the key-value pairs is in the outer dictionary that points to another dictionary. We will see various methods through which we can get all Values from Nested Dictionary.
Example:
Input:
{ "website": "https://www.geeksforgeeks.org",
"founder": {
"name": "Sandeep Jain",
"role": "CEO",
"location": "India"
},
"topics": {
"programming": ["C", "C++", "Java", "Python"],
"web_development": ["HTML", "CSS", "JavaScript", "PHP"],
"data_science": ["Python", "Machine Learning", "Data Analytics"]
}
}
Output:
['https://www.geeksforgeeks.org', 'Sandeep Jain', 'CEO', 'India', 'C',
'C++', 'Java', 'Python', 'HTML', 'CSS', 'JavaScript', 'PHP', 'Python', 'Machine Learning', 'Data Analytics']
Get All Values from a Nested Dictionary
There are different methods to Get All Values from a Nested Dictionary in Python. Below we are explaining all the possible approaches with practical implementation.
- Using Recursion
- Using Stack Data Structure
- Using itertools.chain
- Using json.dumps and json.loads
Get All Values from Nested Dictionary Using Recursion
In this approach, we are using the recursive function apporach1Fn to traverse over the nested input dictionary, we are extracting all values including the nested dictionaries and lists. Then, we store the result in the output object and print it using the print method in Python.
Example: In this example, we are using the Recursive Method to Get All Values from Nested Dictionary.
Python3
def approach1Fn(d):
val = []
for v in d.values():
if isinstance (v, dict ):
val.extend(approach1Fn(v))
elif isinstance (v, list ):
for i in v:
if isinstance (i, dict ):
val.extend(approach1Fn(i))
else :
val.append(i)
else :
val.append(v)
return val
input = {
"founder" : {
"name" : "Sandeep Jain" ,
"role" : "CEO" ,
"location" : "India"
},
"topics" : {
"programming" : [ "C" , "C++" , "Java" , "Python" ],
"web_development" : [ "HTML" , "CSS" , "JavaScript" , "PHP" ],
"data_science" : [ "Python" , "Machine Learning" , "Data Analytics" ]
}
}
output = approach1Fn( input )
print (output)
|
Output:
['https://www.geeksforgeeks.org', 'Sandeep Jain', 'CEO', 'India', 'C', 'C++', 'Java', 'Python', 'HTML', 'CSS',
'JavaScript', 'PHP', 'Python', 'Machine Learning', 'Data Analytics']
Extract All Values from Nested Dictionary Using Stack Data Structure
In this approach, we are using Stack DSA to iteratively traverse over the input dictionary, push the values on the stack, and pop them to accumulate all the values. This property gets the values from the Nested Dictionary and prints them as the output.
Example: In this example, we are using the Stack Data Structure to Get All Values from Nested Dictionary.
Python3
def apprach2Fn(d):
stack = [d]
val = []
while stack:
curr = stack.pop()
if isinstance (curr, dict ):
stack.extend(curr.values())
elif isinstance (curr, list ):
stack.extend(curr[:: - 1 ])
else :
val.append(curr)
return val
input = {
"founder" : {
"name" : "Sandeep Jain" ,
"role" : "CEO" ,
"location" : "India"
},
"topics" : {
"programming" : [ "C" , "C++" , "Java" , "Python" ],
"web_development" : [ "HTML" , "CSS" , "JavaScript" , "PHP" ],
"data_science" : [ "Python" , "Machine Learning" , "Data Analytics" ]
}
}
output = apprach2Fn( input )
print (output)
|
Output:
['Python', 'Machine Learning', 'Data Analytics', 'HTML', 'CSS', 'JavaScript', 'PHP', 'C', 'C++', 'Java',
'Python', 'India', 'CEO', 'Sandeep Jain', 'https://www.geeksforgeeks.org']
Find All Values from Nested Dictionary Using itertools.chain()
In this approach, we use itertools.chain to flatten a nested dictionary by properly handling the string elements extracting all the values from the input ditionary, and printing it using the print method.
Example: In this example, we are using the itertools.chain to Get All Values from Nested Dictionary.
Python3
from itertools import chain
def approach3Fn(d):
return list (chain.from_iterable(
[approach3Fn(v) if isinstance (v, dict ) else [v]
if isinstance (v, str ) else v for v in d.values()]
))
input_data = {
"founder" : {
"name" : "Sandeep Jain" ,
"role" : "CEO" ,
"location" : "India"
},
"topics" : {
"programming" : [ "C" , "C++" , "Java" , "Python" ],
"web_development" : [ "HTML" , "CSS" , "JavaScript" , "PHP" ],
"data_science" : [ "Python" , "Machine Learning" , "Data Analytics" ]
}
}
output = approach3Fn(input_data)
print (output)
|
Output:
['https://www.geeksforgeeks.org', 'Sandeep Jain', 'CEO', 'India', 'C', 'C++', 'Java', 'Python', 'HTML', 'CSS',
'JavaScript', 'PHP', 'Python', 'Machine Learning', 'Data Analytics']
Get All Values from Dictionary Using json.dumps() and json.loads()
In this approach, we are using json.dumps() and json.loads() methods that convert the nested dictionary into the JSON string and then back into a dictionary. We then extract and return the list of all the values from this dictionary and print them as the output.
Example: In this example, we are using the json.dumps() and json.loads() to get all values from Nested Dictionary in Python.
Python3
import json
def approach4Fn(d):
def valFn(i):
if isinstance (i, dict ):
return [value for sub_item in i.values() for value in valFn(sub_item)]
elif isinstance (i, list ):
return [value for sub_item in i for value in valFn(sub_item)]
else :
return [i]
json_str = json.dumps(d)
json_dict = json.loads(json_str)
return valFn(json_dict)
input_data = {
"founder" : {
"name" : "Sandeep Jain" ,
"role" : "CEO" ,
"location" : "India"
},
"topics" : {
"programming" : [ "C" , "C++" , "Java" , "Python" ],
"web_development" : [ "HTML" , "CSS" , "JavaScript" , "PHP" ],
"data_science" : [ "Python" , "Machine Learning" , "Data Analytics" ]
}
}
output = approach4Fn(input_data)
print (output)
|
Output:
['https://www.geeksforgeeks.org', 'Sandeep Jain', 'CEO', 'India', 'C', 'C++', 'Java', 'Python', 'HTML',
'CSS', 'JavaScript', 'PHP', 'Python', 'Machine Learning', 'Data Analytics']
Share your thoughts in the comments
Please Login to comment...