Python Practice › Dictionary Programs › Program 78
Value at a nested path
Write a Python program to get the value at a path of keys and indexes in nested data.
Input
{"p1": {"name": {"first": "lionel", "last": "messi"}, "team": ["psg", "argentina"]}}Output
Messi Argentina
Approach
- Follow the path one step at a time with
functools.reduce.
Solution
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.