从词典字典访问键

时间:2018-08-14 07:00:07

标签: python python-2.7

我有一个字典,例如

expr dictionary[@"key"] = @"newvalue"

我想提取这种格式的所有键。

ab={'apple':7,'ball':9,'src':{'dst':6},'svr':{'pre':{'ere':0}}}

我一直试图以这种方式做

keys=['apple','ball',['src','dst'],['svr','pre','ere']]

有没有更好的方法来解决这个问题?

1 个答案:

答案 0 :(得分:1)

使用递归的一种解决方案:

def get_keys(d:dict):
    out = []
    for key, value in d.items():
        if isinstance(value, dict):
            lst = get_keys(value)
            out.append([key]+lst[0] if isinstance(lst[0], list) else [key] + lst)
        else:
            out.append(key)
    return out

d = {'apple':7,'ball':9,'src':{'dst':6},'svr':{'pre':{'ere':0}}}
print(get_keys(d))

输出:

['apple', 'ball', ['src', 'dst'], ['svr', 'pre', 'ere']]
相关问题