Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Writing a Utility Function

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Writing a Utility Function. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

The Teachable Creator Dashboard receives nested configuration objects, and frontend code often needs to safely read a deeply nested value. Implement a Python equivalent of Lodash's get function.

Given a nested object, a property path, and an optional default value, return the value at that path. The path may be a dot-separated string such as user.profile.name, a bracket-index string such as courses[0].title, or a list of path segments such as ["courses", 0, "title"]. Return the default value only when the path cannot be fully resolved.

For this problem, string paths use non-empty property names and non-negative integer list indexes. Bracket notation does not contain quoted property names.

Formal Specification

Implement lodash_get(obj, path, default_value). obj is a nested combination of dictionaries, lists, strings, numbers, booleans, and None. path is either a string or a list containing strings and integers. Return the resolved value, or default_value if any segment is missing or invalid. A resolved None value is valid and must not be replaced by the default.

Constraints

  • 0 <= number of path segments <= 100
  • Nested objects contain at most 10^4 total values
  • List indexes are non-negative integers
  • A missing path and a resolved None must be distinguished
  • String paths use dot notation and unquoted bracket notation such as items[0].name

Function Signature

def lodash_get(obj, path, default_value):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output