在嵌套的python字典中获取所有键组合

时间:2017-02-20 04:51:03

标签: python dictionary combinations

我是python的新手..试图获得所有的组合键。让我说我有字典d。

d = {'edge': {'edge1': {'interface': {'interface1': {'ip': 10, 'name': 'uplink-to-x'}}, 'name': 'x'}, 'edge2': {'interface': {'interface1': {'ip': 20, 'name': 'uplink-to-y'}}, 'name': 'y'}}}

需要输出:

edge["edge1"]["name"]
edge["edge1"]["interface"]["interface1"]["name"]
edge["edge1"]["interface"]["interface1"]["ip"]
edge["edge2"]["name"]
edge["edge2"]["interface"]["interface1"]["name"]
edge["edge2"]["interface"]["interface1"]["ip"]

请帮助..

2 个答案:

答案 0 :(得分:3)

您可以像这样遍历叶子元素:

Python3代码

d = {'edge': {'edge1': {'interface': {'interface1': {'ip': 10, 'name': 'uplink-to-x'}}, 'name': 'x'}, 'edge2': {'interface': {'interface1': {'ip': 20, 'name': 'uplink-to-y'}}, 'name': 'y'}}}
def nested_print(d):
    for key in d:
        if isinstance(d[key],dict):
            nested_print(d[key])
        else:
            print(key,d[key])
nested_print(d)

<强>输出

ip 20
name uplink-to-y
name y
ip 10
name uplink-to-x
name x

N.B。:我在您的字典中找不到edge["edge1"]["name"]的任何元素

isinstance内置函数的文档可以在这里找到:https://docs.python.org/3/library/functions.html#isinstance

答案 1 :(得分:0)

因为我找不到准备好的函数来将嵌套的字典键转换成元组列表,所以这样写。毫不费力就可以将其转换为纯文本:

def to_tuples(dict_, result_list=None, in_line_list=None):
    """convert from nested dictionaty to list of tuples"""
    is_return_list = True if result_list is None else False
    if is_return_list:
        result_list = []
    is_create_new = True if in_line_list is None else False
    for k, v in dict_.items():
        if is_create_new:
            in_line_list = []
        out_line_list = copy.deepcopy(in_line_list)
        out_line_list.append(k)
        if not isinstance(v, dict) or len(v) == 0:
            result_list.append(tuple(out_line_list))
        else:
            to_tuples(dict_[k], result_list, out_line_list)
    if is_return_list:
        return result_list


d = {
    "edge": {
        "edge1": {"interface": {"interface1": {"ip": 10, "name": "uplink-to-x"}}, "name": "x"},
        "edge2": {"interface": {"interface1": {"ip": 20, "name": "uplink-to-y"}}, "name": "y                                            "},
    }
}


for x in to_tuples(d):
    a = [f"""["{key}"]""" for key in x]
    print("edge" + "".join(a))

将打印:

edge["edge"]["edge1"]["interface"]["interface1"]["ip"]
edge["edge"]["edge1"]["interface"]["interface1"]["name"]
edge["edge"]["edge1"]["name"]
edge["edge"]["edge2"]["interface"]["interface1"]["ip"]
edge["edge"]["edge2"]["interface"]["interface1"]["name"]
edge["edge"]["edge2"]["name"]