从Python中的嵌套字典中获取键的绝对路径

时间:2019-04-29 07:45:00

标签: json python-3.x dictionary

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

示例json对象,键名称为“ year”

{
  "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

1 个答案:

答案 0 :(得分:1)

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')