python字典的递归深度 [英] Recursive depth of python dictionary
问题描述
G'day,
我正在尝试查找拖曳字典的函数的递归深度,我有点失落...
目前我有这样的东西:
I am trying to find the recursive depth of a function that trawls a dictionary and I'm a bit lost... Currently I have something like:
myDict = {'leve1_key1': {'level2_key1': {'level3_key1': {'level4_key_1': {'level5_key1': 'level5_value1'}}}}}
我想知道只是嵌套最嵌套的字典是...所以我做以下...
And I want to know just how nested the most nested dictionary is... so I do the following...
def dict_depth(d, depth):
for i in d.keys():
if type(d[i]) is dict:
newDict = d[i]
dict_depth(newDict, depth+1)
return depth
print dict_depth(myDict, 0)
只有问题是,递归循环只返回最终值(0)的返回值。
如果我在d.keys():中放入一个打印声明
,那么我至少可以打印最高的递归值,但是返回价值是一个不同的事情...
Only problem is, the recursive loop only returns the return of the final value (0).
if I put in a print statement
for i in d.keys():
then I can at least print the highest value of recursion, but returning the value is a different matter...
我确信这是直截了当的 - 我刚刚得到jellybrain。
I'm sure this is straightforward - I've just got jellybrain.
干杯
推荐答案
请确保将递归调用的结果分配给深度 。另外,正如@amit所说,请考虑使用 max ,以便您可以处理具有多个键值对(treelike结构)的列表。
Be sure to assign the result of the recursive call to depth. Also, as @amit says, consider using max so that you can handle dicts with multiple key value pairs (a treelike structure).
def dict_depth(d, depth=0):
if not isinstance(d, dict) or not d:
return depth
return max(dict_depth(v, depth+1) for k, v in d.iteritems())
>>> myDict = {'leve1_key1': {'level2_key1':
{'level3_key1': {'level4_key_1':
{'level5_key1': 'level5_value1'}}}}}
>>> dict_depth(myDict)
5
这篇关于python字典的递归深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!