← Questions

Look up a value in a nested object by path

0
AmazonCodingLast asked Oct 2025

A coding interview question asked in Amazon's technical phone screen, last asked Oct 2025. It tests recursion and parsing.

Given a nested object made of maps and lists inside each other, and a path string such as "a.b.0.c", return the value at that path. Each dot-separated part is a key when the current value is a map, and an index when it is a list. If any step is missing, return a default value instead of raising an error.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • get_path(obj: dict | list, path: str, default=None) — the value at path, or default. An empty path returns obj itself.

Example

obj = {"a": {"b": [{"c": 5}, {"c": 7}]}, "x": [10, 20]}

get_path(obj, "a.b.1.c")         ->  7
get_path(obj, "x.0")             ->  10
get_path(obj, "a.b.2.c")         ->  None      # index out of range
get_path(obj, "a.z", "n/a")      ->  "n/a"     # missing key
get_path(obj, "x.foo")           ->  None      # a list needs a numeric index
get_path(obj, "")                ->  obj

Constraints

  • Nesting depth up to about 100; maps have string keys.
  • Values along the way may be None, numbers or strings, which cannot be stepped into.

Clarifying questions

  • Are negative list indices allowed?
  • Can keys themselves contain dots, and if so how are they escaped?
  • Should a stored None be returned as None or treated as missing?
  • Should bad paths return the default or raise?

What a strong answer covers

  • Split the path and walk it one part at a time, checking the type of the current value at each step: a map needs the key present, a list needs a valid non-negative integer index, anything else ends the walk.
  • Telling "missing" apart from "present but None" with a sentinel.
  • O(length of path) time and O(1) extra space with a loop rather than recursion.
  • Tests: empty path, missing key, index out of range, non-numeric index on a list, stepping into a scalar, very deep nesting.

Follow-ups

  • Write set_path(obj, path, value), creating missing maps and lists along the way.
  • Support bracket syntax such as a.b[0].c and quoted keys that contain dots.
  • Support a wildcard such as a.b.*.c that returns every match.

Where it's asked

  • Amazon · Technical phone screen · Last asked Oct 202560 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI

What it tests

recursion · parsing

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding