Value at a nested path

MediumDictionary Programs · 78 of 94

Write a Python program to get the value at a path of keys and indexes in nested data.

Advertisement
Input
{"p1": {"name": {"first": "lionel", "last": "messi"}, "team": ["psg", "argentina"]}}
Output
Messi
Argentina

Approach

  1. Follow the path one step at a time with functools.reduce.

Solution

Python
from functools import reduce data = {"p1": {"name": {"first": "lionel", "last": "messi"}, "team": ["psg", "argentina"]}} def get_path(obj, path):    return reduce(lambda acc, key: acc[key], path, obj) print(get_path(data, ["p1", "name", "last"]).title())print(get_path(data, ["p1", "team", 1]).title())
Output
Messi
Argentina

Line by line

Lines 5-6

reduce applies acc[key] for each key in turn, starting from the whole object; indexes work for lists.

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs

Leave a Comment