def cut(dict_, maxdepth, replaced_with=None):
    """Cuts the dictionary at the specified depth.
    If maxdepth is n, then only n levels of keys are kept.
    """
queue = collections.deque([(dict_, 0)])
while queue:
    parent, depth = queue.popleft()
for key, child in list(parent.items()):
    if isinstance(child, dict):
        if depth == maxdepth - 1:
            parent[key] = replaced_with
else:
    queue.append((child, depth + 1))
How to cut a very "deep" json or dictionary in Python?