Collect Every Value Stored Under a Key in Nested Data
Trees & GraphsAuto-graded · 19 test casesLast updated
Walk a nested structure of dicts and lists depth-first and gather every value stored under a given key, in traversal order, including matches inside already-matched values.
Gather Values by Key in a Nested Document
You are given a document built from JSON-style data. It may contain dictionaries (string keys), lists, and primitive values (str, int, float, bool, None), nested in any combination and to any depth.
Write a function that returns every value stored under a given key anywhere in the document.
Rules
- Whenever a dictionary has an entry whose key equals
target_key, add that entry's value to the result. - A value that was added must still be searched. If it is a dictionary or list, look inside it for more occurrences of
target_key. - Lists have no keys. Visit their elements from first to last. A string element that happens to equal
target_keyis not a match, because only dictionary keys count. - The result must follow pre-order depth-first order:
- Go through a dictionary's entries in their stored (insertion) order.
- When an entry matches, record its value before exploring inside that value.
- Fully finish one entry's subtree before moving to the next entry.
- Key comparison is case-sensitive and exact.
- Every occurrence counts, so equal values found in different places each appear in the result.
- Values such as
None,{},[],0,Falseand""are ordinary values and must be included when they sit under a matching key. - If the key never appears (including when the root is a primitive, an empty dict, or an empty list), return an empty list.
- Matched values may be returned as references to the original objects; no copying is needed.
Constraints
- The document contains only
dict,list,str,int,float,bool, andNone. - Dictionary keys are strings.
- Nesting depth is at most 500.
- The total number of dictionary entries and list elements is at most
10^5.
Examples
Example 1
Input: collect_values_for_key({'user': {'id': 101, 'name': 'Alice', 'metadata': {'id': 'sub_101', 'status': 'active'}}, 'tags': ['admin', 'staff'], 'id': 999}, 'id')
Output: [101, 'sub_101', 999]
Example 2
Input: collect_values_for_key({'item': 'top-level'}, 'item')
Output: ['top-level']
Hints
Hint 1
Treat the document as a tree: dictionaries and lists are internal nodes, primitives are leaves where recursion stops.
Hint 2
For each dictionary entry, first check whether the key matches and record the value, then recurse into that value whether or not it matched.
Hint 3
Use a single shared result list that you append to during the traversal, and test for matches with key equality rather than truthiness so that None, 0, and empty containers are kept.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The document is a tree. Dictionaries and lists are internal nodes, and primitives are leaves. The task is a pre-order depth-first traversal that records matches as it goes.
- Dictionary: iterate over
(key, child)pairs in insertion order. Ifkey == target_key, appendchildto the results. Then recurse intochildregardless of whether it matched, since a matched value can contain further occurrences. - List: recurse into each element in order. Nothing is appended at this level because lists have no keys.
- Primitive: do nothing. This is the base case.
A shared results list is used as an accumulator, which avoids the repeated copying that comes from concatenating lists returned by each recursive call.
Why It Is Correct
Every node is reached exactly once: the root is visited, each dictionary value and list element is visited from its parent, and primitives end the recursion. A value belongs in the output exactly when it sits directly under a dictionary key equal to target_key, and the dictionary branch tests exactly that condition for every entry. So every qualifying value is added and nothing else is.
Order follows from the traversal. For each entry, the match is appended before descending, and the whole subtree is explored before the next sibling, which is pre-order DFS. Because matches are tested with == on keys and not by truthiness, values like None, 0, {} and [] are kept. Strings inside lists are never compared, so they cannot produce false matches.
Complexity
- Time: O(N), where N is the total number of dictionary entries and list elements. Each is processed once.
- Space: O(D + M), where D is the maximum nesting depth (recursion stack) and M is the number of matches. With depth at most 500, this fits within CPython's default recursion limit.
Reference Solution
from typing import Any, List
def collect_values_for_key(document: Any, target_key: str) -> List[Any]:
results = []
def visit(node):
if isinstance(node, dict):
for key, child in node.items():
if key == target_key:
results.append(child)
visit(child)
elif isinstance(node, list):
for child in node:
visit(child)
visit(document)
return results