Python Get All Values from Nested Dictionary
Last Updated :
19 Jan, 2024
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
# Using recursion to get all values from nested dictionary
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 = {
"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 = 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
# Using Stack to get all values from nested dictionary
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 = {
"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 = 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
input_data = {
"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 = 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 = {
"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 = 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']
Similar Reads
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
Get all Tuple Keys from Dictionary - Python
In Python, dictionaries can have tuples as keys which is useful when we need to store grouped values as a single key. Suppose we have a dictionary where the keys are tuples and we need to extract all the individual elements from these tuple keys into a list. For example, consider the dictionary : d
3 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 Dictionary Value by Key - Python
We are given a dictionary and our task is to retrieve the value associated with a given key. However, if the key is not present in the dictionary we need to handle this gracefully to avoid errors. For example, consider the dictionary : d = {'name': 'Alice', 'age': 25, 'city': 'New York'} if we try t
3 min read
Get Python Dictionary Values as List - Python
We are given a dictionary where the values are lists and our task is to retrieve all the values as a single flattened list. For example, given the dictionary: d = {"a": [1, 2], "b": [3, 4], "c": [5]} the expected output is: [1, 2, 3, 4, 5] Using itertools.chain()itertools.chain() function efficientl
2 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 | 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 Dictionary by Multiple Values
We are given a nested dictionary and our task is to sort a nested dictionary by multiple values in Python and print the result. In this article, we will see how to sort a nested dictionary by multiple values in Python. Example: Input : {'A': {'score': 85, 'age': 25}, 'B': {'score': 92, 'age': 30}, '
3 min read
Python Print Dictionary Keys and Values
When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values. Example: Using print() Method [GFGTABS] Python my_dict = {'a': 1, 'b'
2 min read
Get Unique Values from List of Dictionary
We are given a list of dictionaries and our task is to extract the unique values from these dictionaries, this is common when dealing with large datasets or when you need to find unique information from multiple records. For example, if we have the following list of dictionaries: data = [{'name': 'A
4 min read