Python:检查嵌套字典中的特定键,如果匹配则返回所有先前的键

时间:2018-09-06 17:12:34

标签: python python-2.7

我有一个嵌套的字典,我想遍历整个字典以检查特定的键。如果匹配,我想返回所有经过迭代以达到该特定键的键。

My Dictionary:

d = {
    "aaa":{
        "bbb":"xyz",
        "ccc":{
            "description":"xyz",
            "data":"abc"
        }
        "description":"xyz"
    }
    "xxx":{
        "description":"xyz",
        "bbb":{
            "ccc":{
                "ddd":{
                    "description":"xyz"
                }
            }
        }
    }
}

Excpected output:

aaa--description
aaa--ccc--description
xxx--description
xxx--bbb--ccc--ddd--description

我尝试了以下代码,但未获得预期的输出

tmp_str = ""
def iter_dict(d):
    global tmp_str
    for key in sorted(d.keys()):
        if type(d[key]) == dict and len(d[key]) > 0:
            tmp_str += "--%s" %key
            iter_dict(d[key])
        elif key == "description":
            tmp_str += "--%s\n" %(key)

for key in d.keys():
    tmp_str += "\n\n%s" %key
    iter_dict(d[key])
print tmp_str

请分享您的想法..谢谢

2 个答案:

答案 0 :(得分:1)

您需要跟踪递归时看到的键。只需在您的iter_dict函数中添加参数,然后在其中按下/弹出键即可。

也:请勿使用此全局tmp_str,只需返回该值即可。

def iter_dict(d, rec_keys=None):
    rec_keys = rec_keys or []
    results = []
    for key, value in sorted(d.items(), key=lambda x: x[0]):
        if isinstance(value, dict) and value:
            results.append(iter_dict(value, rec_keys + [key]))
        elif key == "description":
            results.append('--'.join(rec_keys + ['description']))
    return '\n'.join(results)

tmp_str = iter_dict(d)

结果是:

>>> print(tmp_str)
aaa--ccc--description
aaa--description
xxx--bbb--ccc--ddd--description
xxx--description

我将把行的顺序留给您作为练习。

答案 1 :(得分:1)

使用递归生成器的一种方法:

d = {
    "aaa":{
        "bbb":"xyz",
        "ccc":{
            "description":"xyz",
            "data":"abc"
        },
        "description":"xyz"
    },
    "xxx":{
        "description":"xyz",
        "bbb":{
            "ccc":{
                "ddd":{
                    "description":"xyz"
                }
            }
        }
    }
}


def paths_to_key(key, d, current_path=None):
    if current_path is None:
        current_path = []

    for k, v in d.items():
        if k == key:
            yield current_path + [key]
        else:
            if isinstance(v, dict):
                path = current_path + [k]
                yield from paths_to_key(key, v, path)

for path in paths_to_key('description', d):
    print(path)

输出:

['xxx', 'description']
['xxx', 'bbb', 'ccc', 'ddd', 'description']
['aaa', 'ccc', 'description']
['aaa', 'description']