在嵌套的json / dict中搜索与指定键匹配的多个键值

时间:2018-09-28 16:29:50

标签: python json dictionary nested

我有一个Python对象,其中包含多层字典和列表,其中包含我需要从中获取值的键。我发现使用递归生成器的answer允许我提取一个键的值,但不能提取多个键。这是代码:

with open('data.json') as f:
    json_data = json.load(f)

def find_key(obj, key):
    if isinstance(obj, dict):
        yield from iter_dict(obj, key, [])
    elif isinstance(obj, list):
        yield from iter_list(obj, key, [])

def iter_dict(d, key, indices):
    for k, v in d.items():
        if k == key:
            yield indices + [k], v
        if isinstance(v, dict):
            yield from iter_dict(v, key, indices + [k])
        elif isinstance(v, list):
            yield from iter_list(v, key, indices + [k])

def iter_list(seq, key, indices):
    for k, v in enumerate(seq):
        if isinstance(v, dict):
            yield from iter_dict(v, key, indices + [k])
        elif isinstance(v, list):
            yield from iter_list(v, key, indices + [k])


for c in find_key(json_data, 'customer_count'):
    print(c)

结果:

(['calendar', 'weeks', 0, 'days', 1, 'availabilities', 0, 'customer_count'], 14)
(['calendar', 'weeks', 0, 'days', 2, 'availabilities', 0, 'customer_count'], 7)

另一个post有一个示例可以提取多个键,但不会遍历整个对象:

[...]
keys = ("customer_count", "utc_start_at", "non_resource_bookable_capacity")
for k in keys:
    keypath, val = next(find_key(json_data, k))
    print("{!r}: {!r}".format(k, val))

结果:

'customer_count': 14
'utc_start_at': '2018-09-29T16:45:00+0000'
'non_resource_bookable_capacity': 18

如何遍历整个对象并提取上面显示的三个键?

我想要的结果看起来像这样:

'customer_count': 14
'utc_start_at': '2018-09-29T16:45:00+0000'
'non_resource_bookable_capacity': 18

'customer_count': 7
'utc_start_at': '2018-09-29T16:45:00+0000'
'non_resource_bookable_capacity': 25

sample json

1 个答案:

答案 0 :(得分:0)

下面的示例函数在dict(包括所有嵌套dict)上搜索与您要查找的键列表匹配的键/值对。此函数以递归方式遍历字典和所有嵌套的字典,并列出其中包含的内容,以构建所有可能的字典的列表,以检查是否有匹配的键。

def find_key_value_pairs(q, keys, dicts=None):
    if not dicts:
        dicts = [q]
        q = [q]  

    data = q.pop(0)
    if isinstance(data, dict):
        data = data.values()

    for d in data:
        dtype = type(d)
        if dtype is dict or dtype is list:
            q.append(d)
            if dtype is dict:
                dicts.append(d)

    if q:
        return find_key_value_pairs(q, keys, dicts)

    return [(k, v) for d in dicts for k, v in d.items() if k in keys]

下面的示例在将其传递给函数之前,使用json.loads将类似于json的示例数据集转换为字典。

import json

json_data = """
{"results_count": 2, "results": [{"utc_start_at": "2018-09-29T16:45:00+0000", "counts": {"customer_count": "14", "other_count": "41"}, "capacity": {"non-resource": {"non_resource_bookable_capacity": "18", "other_non_resource_capacity": "1"}, "resource_capacity": "10"}}, {"utc_start_at": "2018-10-29T15:15:00+0000", "counts": {"customer_count": "7", "other_count": "41"}, "capacity": {"non-resource": {"non_resource_bookable_capacity": "25", "other_non_resource_capacity": "1"}, "resource_capacity": "10"}}]}
"""
data = json.loads(json_data) # json_data is a placeholder for your json
keys = ['results_count', 'customer_count', 'utc_start_at', 'non_resource_bookable_capacity']
results = find_key_value_pairs(data, keys)
for k, v in results:
    print(f'{k}: {v}')
# results_count: 2
# utc_start_at: 2018-09-29T16:45:00+0000
# utc_start_at: 2018-10-29T15:15:00+0000
# customer_count: 14
# customer_count: 7
# non_resource_bookable_capacity: 18
# non_resource_bookable_capacity: 25