[英]Trim python dictionary based on stop recursion level
Let's say I have the following Python dictionary:假设我有以下 Python 字典:
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.如何基于停止级别创建一个新对象,它类似于上面的
resurse_stop
函数,但它不是打印数据,而是构建一个对象。 Let's call the function resurse_stop_obj
and here are some examples of what it should return:让我们调用函数
resurse_stop_obj
,下面是它应该返回的一些示例:
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:将您的
print
表达式包装成字典理解:
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: {}}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.