I'm using Python 3.8.0 and I try to write a function which extracts all the keys of nested dictionaries and gathers the result in a list. Here is an example:
mydict = {"k1":"v1", "k2":"v2", "k3":{"k4":"v4","k5":{"k6":{"k7":"v7","k8":"v8"}}}}
What I expect as the output is:
[k1, k2, k3, k4, k5, k7, k8]
Here is a recursive function that I've defined :
def extract_dict_keys(d):
if isinstance(d, dict):
result = []
for k, v in d.items():
if isinstance(v, dict):
result.append(k).extend(extract_dict_keys(v))
else:
result.append(k)
return result
else:
[None]
But when I call extract_dict_keys(mydict) I get the following error message:
>>> extract_dict_keys(mydict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in extract_dict_keys
AttributeError: 'NoneType' object has no attribute 'extend'
>>>
Could you kindly indicate what I misunderstand? I don't see the problem.