This does what you want:
M ={'data': 'k', 'list':{
'data': 'c', 'list' : {
'data': 'i', 'list' : {
'data': 's', 'list':False}}}}
from collections import abc
def nested_dict_iter(nested):
for key, value in nested.items():
if isinstance(value, abc.Mapping):
yield from nested_dict_iter(value)
else:
yield value
print(''.join(reversed(list(nested_dict_iter(M))[:-1])))
Output:
sick
Some explanation:
From this answer, a dict is iterable and therefore you can apply the nested container iterable formula to this problem. This allows you to loop through the nested dictionary, while the yield
returns a generator one item at a time.
Since the dictionary is nested, with one element at each depth, order is irrelevant. Finally, I converted the generator to a list, removed the last element (which is False
) and then joined a reversed version of the list, which outputs the correct string.