如何在嵌套字典中迭代第n个位置

时间:2018-06-29 10:38:03

标签: python json python-3.x dictionary

我有一个长度不固定的嵌套字典。

[{'name': 'stack', 'children': [{'name': 'flow', 'children': [{'name': 'lldp', 'children': [{'name': 'sourc', 'children': [{'name': 'lldque.jrc', 'count': '11', 'size': '37'}]}]}, {'name': 'arp', 'children': [{'name': 'src', 'children': [{'name': 'arpred.cec', 'count': '37', 'size': '67'}]}]}]}]}]

我要访问dict中的最后一个dict键(“ count”和“ size”)。

我已经尝试过以下功能,但无法正常工作。

def get_value(your_dict,*keys):
    curr_dict = your_dict
    for k in keys:
        v = curr_dict.get(k,None)
        if v is None:
            break
        if isinstance(v,dict):
            curr_dict = v
    return v

4 个答案:

答案 0 :(得分:0)

您可以递归获取所有这些信息:

from itertools import chain
def get_value(your_dict,*keys):
    if "children" in your_dict:
        return tuple(
          chain.from_iterable(
            get_value(d, *keys) for d in your_dict["children"]
            )
        )
    return tuple(your_dict[k] for k in keys if k in your_dict)

您在这里有一个live example

答案 1 :(得分:0)

您有一个递归字典,因此您可能需要使用递归。试试这个:

def get_value(d):
    if 'count' in d and 'size' in d:
        return d['count'], d['size']
    elif 'children' in d:
        return get_value['children']

请注意,这只会返回找到的第一个元素的数量和大小。您可以轻松地使它检查名称。如果找不到叶节点,它将返回None

答案 2 :(得分:0)

我们可以创建一些递归函数来搜索key,如下所示:

def search_data_key(data, key):
    if key in data:
        yield data[key]
    for k in data:
        if isinstance(data[k], list):
            for i in data[k]:
                for j in search_data_key(i, key):
                    yield j

data = [{'name': 'stack', 'children': [{'name': 'flow', 'children': [{'name': 'lldp', 'children': [{'name': 'sourc', 'children': [{'name': 'lldque.jrc', 'count': '11', 'size': '37'}]}]}, {'name': 'arp', 'children': [{'name': 'src', 'children': [{'name': 'arpred.cec', 'count': '37', 'size': '67'}]}]}]}]}]

print(list(search_data_key(data[0], 'count')))
print(list(search_data_key(data[0], 'size')))

output:

['11', '37']
['37', '67']

答案 3 :(得分:0)

这是一个常规实现,它递归扫描您的结构,如果它是dict

def find_key_in_nested(struct, key, result_list):
    # Check if it is a list and loop over all elements
    if type(struct) == list:
        for it in struct:
            element = find_key_in_nested(it, key, result_list)
            if element:
                result_list.append(element)
    # Check if it is a dict
    if type(struct) == dict:
        if key in struct.keys(): # It has the required key! Append
            return result_list.append(struct[key])
        # It doesn't have it, keep looking further down
        for k in struct.keys(): 
            element = find_key_in_nested(struct[k], key, result_list)
            if element:
                result_list.append(element)  

它将结果附加在list中,因此您可以像这样称呼

my_list = []
find_key_in_nested(my_dict, 'size', my_list)
print(my_list)

output:
['37', '67']