Skip to main content

Handling Dictionaries

Cutting the first n levels of a dict

def cut_dict(d: dict, n: int, _output=None) -> dict:
"""Cut dictionary d by n levels.
Keys that are not deep enough are thrown out.
If there are same name keys in the n-th level, last key wins.

Args:
d (dict): Dictionary to cut
n (int): Cut by this amount of levels
_output (None): Do not pass anything here. Internal recursion use.
"""
if _output is None:
_output = {}

if n > 0: # Need to go deeper
for value in d.values():
if isinstance(value, dict):
cut_dict(value, n - 1, _output)
else: # Reached the level we want
_output.update(d)

return _output