I have a generator that iterates over all combinations of keys up to a particular depth in a nested dictionary:
def iter_dict(levels, input_dict, items=[], sort=False, **sort_args):
for dict_key, val in (sorted(input_dict.items(), **sort_args) if
sort else input_dict.items()):
if levels == 1:
yield items + [(dict_key, val)]
else:
yield from iter_dict(levels - 1, val, items + [(dict_key, val)])
So it acts like so:
>>> d = {'a': 1, 'b': 2}
>>> list(iter_dict(1, d))
[[('a', 1)], [('b', 2)]]
And
>>> d = {'a': {'c': 1}, 'b': {'d' : 2}}
>>> list(iter_dict(1, d))
[[('a', {'c': 1})], [('b', {'d': 2})]]
>>> list(iter_dict(2, d))
[[('a', {'c': 1}), ('c', 1)], [('b', {'d': 2}), ('d', 2)]]
Each iteration on the generator returns a list of tuples, with the nth tuple being (key, value)
at a depth of n into the nested dictionary.
But I am implementing this function on huge dictionaries and am worried about reaching the maximum recursion depth level.
How can I rewrite the generator to remove the recursion?