python获取多层字典的key
时间: 2023-09-12 19:11:24 浏览: 87
python提取字典key列表的方法
可以使用递归函数来获取多层字典的key,例如:
```python
def get_keys(d, keys=[]):
for k, v in d.items():
keys.append(k)
if isinstance(v, dict):
get_keys(v, keys)
return keys
```
使用示例:
```python
d = {
"key1": {
"key2": {
"key3": "value",
"key4": "value"
},
"key5": "value"
},
"key6": "value"
}
keys = get_keys(d)
print(keys)
```
输出结果:
```
['key1', 'key2', 'key3', 'key4', 'key5', 'key6']
```
阅读全文