首页 > 解决方案 > 从Python中的嵌套字典中获取键的绝对路径

问题描述

我在 python 中有一个字典对象,我会给一个方法提供两个参数,一个是一些键名键和一个 json 对象,我想接收一个具有键的绝对路径的输出。

示例 json 对象和键名是“年”

{
  "name": "John",
  "age": 30,
  "cars": {
    "car1": {
      "name": "CD300",
      "make": {
        "company": "Benz",
        "year": "2019"
      }
    }
  }
}

我的功能将如下所示

def get_abs_path(json, key):
    print(res)

预期输出 res = cars.car1.make.company

标签: jsonpython-3.xdictionary

解决方案


def is_valid(json, key):
    if not isinstance(json, dict):
        return None
    if key in json.keys():
        return key
    ans = None
    for json_key in json.keys():
        r = is_valid(json[json_key], key)
        if r is None:
            continue
        else :
            ans = "{}.{}".format(json_key, r)
    return ans

a = {
    "name": "John",
    "age": 30,
    "cars": {
        "car1": {
            "name": "CD300",
            "make": {
                "company": "Benz",
                "year": "2019"
            }
        }
    }
}
def get_abs_path(json, key):
    path = is_valid(json, key)
    print(path)

get_abs_path(a, 'company')

推荐阅读