MST

星途 面试题库

面试题:Python字典嵌套字典的复杂查找

给定一个嵌套字典结构,例如d = {'A': {'B': {'C': [1, 2, 3], 'D': {'E': 42}}}, 'F': {'G': 55}}。编写一个函数,接受两个参数,第一个参数是嵌套字典,第二个参数是一个键路径列表(例如['A', 'B', 'D', 'E']),函数需要根据键路径找到对应的值并返回。如果路径不存在,返回None。
26.1万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
def get_value_by_path(dictionary, path):
    current = dictionary
    for key in path:
        if not isinstance(current, dict) or key not in current:
            return None
        current = current[key]
    return current