获取所有子字典的键



我有一个这样的字典,其中的值也是字典字典中可以有嵌套的字典。这样的:

data = {'key1': {
'keya':{ 
'keyc': None
}    
'keyb': None

}
'key2': {
'keyi':None, 
'keyii': None
}
}

字典可以有很多(我们不知道值里面有多少字典)。如何获得所有值中的所有键?

['key1', 'key2', 'keya', 'keyb', 'keyi', 'keyii']

您可以使用递归获得所有键

def get_all_keys_rec(dic):
keys = [key for key in dic]
for val in dic.values():
if type(val)==dict:
inner_keys = get_all_keys_rec(val)
keys.extend(inner_keys)
return keys
print(get_all_keys_rec(data))

输出:

['key1', 'key2', 'keya', 'keyb', 'keyc', 'keyi', 'keyii']
keys = []
for key, val in data.items():
keys.append(key)
if isinstance(val, dict):
item = val
while True:
for k, v in item.items():
keys.append(k)
if isinstance(v, dict):
item = v
break
else:
break
print(keys)

这个输出:

['key1', 'keya', 'keyc', 'key2', 'keyi', 'keyii']

递归生成,yield from应该是您的合作伙伴:

>>> data = {'key1': {
...     'keya': {
...         'keyc': None
...     },
...     'keyb': None
...
... },
...     'key2': {
...         'keyi': None,
...         'keyii': None
...     }
... }
>>> def get_all_keys(dct):
...     def gen_all_keys(d):
...         if isinstance(d, dict):
...             yield from d
...             for v in d.values():
...                 yield from gen_all_keys(v)
...     return list(gen_all_keys(dct))
...
>>> get_all_keys(data)
['key1', 'key2', 'keya', 'keyb', 'keyc', 'keyi', 'keyii']

相关内容

  • 没有找到相关文章

最新更新