【问题标题】:get keys from nested dict JSON without hardcode the middle keys从嵌套的 dict JSON 中获取键,无需对中间键进行硬编码
【发布时间】:2021-11-05 13:31:24
【问题描述】:

想从字典中获取 MetaEntry 数据,但每次键名不同时有一些随机名称。

例如:['Client']

dictionary = {
    "Tags":[],
    "ObjectId":
    "ab9c6448-85fe-eb11-b563-281878c3a7fe",
    "Client": {
        "MetaData": {
            "MetaEntry": [
                {
                    "Key": "status",
                    "Value": "Active"
                    },
                {
                    "Key": "first_day_of_week",
                    "Value": "Monday"
                    },
                {
                    "Key": "default_induction_expiry",
                    "Value": "0"
                    }
                ]
            },
        "RelatedLinks": [],
        "Tags": [],
        "ObjectId": "6cf54386-d81a-eb11-9fb4-281878b13795",
        "Type": "Artifice.Web.Data.Entities.Client",
        "Name": "Amco Logictics "
        }
    }

打印(字典['Client']['MetaData']['MetaEntry'])

这里['Client'] 键会随机变化,所以我上面的打印乐趣将不起作用,有没有一种解决方法可以在不硬编码['Client'] 键的情况下获得['MetaData']['MetaEntry']

【问题讨论】:

标签: python json python-3.x dictionary


【解决方案1】:

如果你有深度嵌套的字典,你可以递归遍历找到所有MetaEntry键:

dictionary = {
    "Tags": [],
    "ObjectId": "ab9c6448-85fe-eb11-b563-281878c3a7fe",
    "Client": {
        "MetaData": {
            "MetaEntry": [
                {"Key": "status", "Value": "Active"},
                {"Key": "first_day_of_week", "Value": "Monday"},
                {"Key": "default_induction_expiry", "Value": "0"},
            ]
        },
        "RelatedLinks": [],
        "Tags": [],
        "ObjectId": "6cf54386-d81a-eb11-9fb4-281878b13795",
        "Type": "Artifice.Web.Data.Entities.Client",
        "Name": "Amco Logictics ",
    },
}


def find(d):
    if isinstance(d, dict):
        if "MetaEntry" in d:
            yield d["MetaEntry"]
        else:
            for k, v in d.items():
                yield from find(v)
    elif isinstance(d, list):
        for v in d:
            yield from find(v)


for meta_entry in find(dictionary):
    print(meta_entry)

打印:

[
    {"Key": "status", "Value": "Active"},
    {"Key": "first_day_of_week", "Value": "Monday"},
    {"Key": "default_induction_expiry", "Value": "0"},
]

编辑:打印当前路径:

def find(d, cur_path=None):
    if cur_path is None:
        cur_path = []

    if isinstance(d, dict):
        if "MetaEntry" in d:
            yield d["MetaEntry"], cur_path + ["MetaEntry"]
        else:
            for k, v in d.items():
                yield from find(v, cur_path + [k])
    elif isinstance(d, list):
        for i, v in enumerate(d):
            yield from find(v, cur_path + [i])


for meta_entry, cur_path in find(dictionary):
    print(cur_path)
    print(meta_entry)

打印:

['Client', 'MetaData', 'MetaEntry']

[{'Key': 'status', 'Value': 'Active'}, {'Key': 'first_day_of_week', 'Value': 'Monday'}, {'Key': 'default_induction_expiry', 'Value': '0'}]

【讨论】:

  • 有没有办法在这个函数中获取Keys-path,例如:dictionary['Client']['MetaData']['MetaEntry']。像这样
【解决方案2】:

下面的代码将处理'Client'将被其他字符串替换的情况

data = {"Tags": [], "ObjectId": "ab9c6448-85fe-eb11-b563-281878c3a7fe", "kkk": {"MetaData": {
    "MetaEntry": [{"Key": "status", "Value": "Active"}, {"Key": "first_day_of_week", "Value": "Monday"},
                  {"Key": "default_induction_expiry", "Value": "0"}]}, "RelatedLinks": [], "Tags": [],
                                                                                                "ObjectId": "6cf54386-d81a-eb11-9fb4-281878b13795",
                                                                                                "Type": "Artifice.Web.Data.Entities.Client",
                                                                                                "Name": "Amco Logictics "}}


for k,v in data.items():
    if isinstance(v,dict) and 'MetaData' in v:
        print(f'{k} points to metadata')

输出

kkk points to metadata

【讨论】:

    猜你喜欢
    • 2020-07-22
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 2019-09-22
    • 2023-01-12
    相关资源
    最近更新 更多