简体   繁体   中英

Trim python dictionary based on stop recursion level

Let's say I have the following Python dictionary:

d = {1: {2: {3: {}}, 6: {7: {}}, 8: {}, 9: {}}, 10: {11: {}}}

I can recursively traverse up to a certain level in the object using the following function:

def resurse_stop(d, stop=None, curr=0):
    if stop and curr == stop:
        return
    for k, v in d.items():
        print(f"{k} (level={curr})")
        if v:
            resurse_stop(v, stop, curr + 1)

resurse_stop(d, 1)
# 1 (level=0)
# 10 (level=0)

resurse_stop(d, 2)
# 1 (level=0)
# 2 (level=1)
# 6 (level=1)
# 8 (level=1)
# 9 (level=1)
# 10 (level=0)
# 11 (level=1)

How can I create a new object based on the stop level, which is similar to the resurse_stop function above but instead of printing the data, it builds an object. Let's call the function resurse_stop_obj and here are some examples of what it should return:

resurse_stop(d, 1)
# d = {1: {}, 10: {}}

resurse_stop(d, 2)
# d = {1: {2: {}, 6: {}, 8: {}, 9: {}}, 10: {11: {}}}

Wrap your print expression into a dict comprehension:

d = {1: {2: {3: {}}, 6: {7: {}}, 8: {}, 9: {}}, 10: {11: {}}}

def resurse_stop(d, stop=None, curr=0):
    if stop and curr == stop:
        return {}

    return {k: {} if not v else resurse_stop(v, stop, curr + 1)
               for k, v in d.items() }

print(resurse_stop(d, 2))

Output:

{1: {2: {}, 6: {}, 8: {}, 9: {}}, 10: {11: {}}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM