Python - Extract values of Particular Key in Nested Values
Last Updated :
30 Jan, 2025
Improve
We are given a nested dictionary we need to extract the values of particular key. For example, we are having a dictionary d = {'a': 1,'b': {'a': 2, 'c': 3},'d': [{'a': 4}, {'a': 5}]} we need to to extract values from it. so that output becomes [1, 5, 4, 2].
Using a Stack
We can manually manage a stack to iterate through the nested dictionary and lists.
d = {'a': 1,'b': {'a': 2, 'c': 3},'d': [{'a': 4}, {'a': 5}]}
key = 'a'
s = [d]
values = []
# Loop to process the stack until it's empty
while s:
c = s.pop()
if isinstance(c, dict):
# Iterate through dictionary's key-value pairs
for k, v in c.items():
if k == key:
values.append(v)
elif isinstance(v, (dict, list)):
s.append(v)
# If the element is a list
elif isinstance(c, list):
s.extend(c)
print(values)
d = {'a': 1,'b': {'a': 2, 'c': 3},'d': [{'a': 4}, {'a': 5}]}
key = 'a'
s = [d]
values = []
# Loop to process the stack until it's empty
while s:
c = s.pop()
if isinstance(c, dict):
# Iterate through dictionary's key-value pairs
for k, v in c.items():
if k == key:
values.append(v)
elif isinstance(v, (dict, list)):
s.append(v)
# If the element is a list
elif isinstance(c, list):
s.extend(c)
print(values)
Output
[1, 5, 4, 2]
Explanation:
- Code uses a stack to explore a nested dictionary/list, processing each element without recursion.
- It collects values of specified key from dictionaries adding nested dictionaries/lists to stack for further exploration.
Using a Queue
Alternatively we can use a queue to explore structure in a breadth-first manner.
from collections import deque
d = {'a': 1,'b': {'a': 2, 'c': 3},'d': [{'a': 4}, {'a': 5}]}
key = 'a'
q = deque([d])
values = []
# Loop to process the queue until it's empty
while q:
c = q.popleft()
if isinstance(c, dict):
# Iterate through the dictionary's key-value pairs
for k, v in c.items():
# If the key matches
if k == key:
values.append(v)
# If the value is a dictionary or list
elif isinstance(v, (dict, list)):
q.append(v)
elif isinstance(c, list):
q.extend(c)
print(values)
from collections import deque
d = {'a': 1,'b': {'a': 2, 'c': 3},'d': [{'a': 4}, {'a': 5}]}
key = 'a'
q = deque([d])
values = []
# Loop to process the queue until it's empty
while q:
c = q.popleft()
if isinstance(c, dict):
# Iterate through the dictionary's key-value pairs
for k, v in c.items():
# If the key matches
if k == key:
values.append(v)
# If the value is a dictionary or list
elif isinstance(v, (dict, list)):
q.append(v)
elif isinstance(c, list):
q.extend(c)
print(values)
Output
[1, 2, 4, 5]
Explanation:
- Code uses a queue (deque) to traverse a nested dictionary/list structure level by level processing each element iteratively.
- It collects values of specified key from dictionaries and adds nested dictionaries/lists to queue for further exploration.
Iterate Through Structure
If we know structure is only a few levels deep (e.g., a dictionary containing lists or other dictionaries) we can use direct iteration without recursion or extra data structures.
d = {'a': 1, 'b': {'a': 2, 'c': 3}, 'd': [{'a': 4}, {'a': 5}]}
key = 'a'
values = []
for k, v in d.items():
if k == key:
values.append(v)
# If the value is a dictionary, iterate through its items
elif isinstance(v, dict):
for k2, v2 in v.items():
# If the key matches in the nested dictionary append the value
if k2 == key:
values.append(v2)
# If the value is a list iterate through its elements
elif isinstance(v, list):
for item in v:
if isinstance(item, dict):
for k2, v2 in item.items():
if k2 == key:
values.append(v2)
print(values)
d = {'a': 1, 'b': {'a': 2, 'c': 3}, 'd': [{'a': 4}, {'a': 5}]}
key = 'a'
values = []
for k, v in d.items():
if k == key:
values.append(v)
# If the value is a dictionary, iterate through its items
elif isinstance(v, dict):
for k2, v2 in v.items():
# If the key matches in the nested dictionary append the value
if k2 == key:
values.append(v2)
# If the value is a list iterate through its elements
elif isinstance(v, list):
for item in v:
if isinstance(item, dict):
for k2, v2 in item.items():
if k2 == key:
values.append(v2)
print(values)
Output
[1, 2, 4, 5]
Explanation:
- Iterates through the top-level dictionary checking for the specified key and exploring nested dictionaries or lists.
- Checks nested dictionaries and lists for key matches appending values to the result list.