【问题标题】:Get absolute path of a key from nested dictionary in Python从Python中的嵌套字典中获取键的绝对路径
【发布时间】:2019-04-29 07:45:00
【问题描述】:

我在 python 中有一个字典对象,我会给一个方法提供两个参数,一个是键名 key 和一个 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

【问题讨论】:

  • 你想要key的abs路径吗?
  • 在这种情况下 get_abs_path(json, 'year') 将返回 cars.car1.make.year 对吗? @Ashwin S
  • @AsifMohammed 是的

标签: json python-3.x dictionary


【解决方案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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 2018-11-02
    • 2018-12-24
    • 2021-05-10
    • 2016-05-15
    • 2013-02-19
    • 1970-01-01
    相关资源
    最近更新 更多