-2

For example, if we have a dict like {a: {b: c}, d: e}, then the max level for this dict is 2.

I've been thinking about the method to find the max level of an arbitrary dict for 2 days, but didn't figure out a solution.

How to do that?

Zen
  • 4,381
  • 5
  • 29
  • 56
  • 1
    So you are looking for an integer here? What problem are you trying to solve? – Martijn Pieters Dec 02 '14 at 13:01
  • @MartijnPieters, Yes, I'm trying to solve the eight queen puzzle, with the representation of dictionary trees. Like, `result={(1,2):{(3.4):{...}}}`, so if a sub_item of result have the depth of 8, then it is one of the solution. – Zen Dec 02 '14 at 13:04

1 Answers1

2

Using recursion:

def nested_depth(d):
    if not isinstance(d, dict):
        return 0
    if not d:
        return 1
    return 1 + max(nested_depth(v) for v in d.values())
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Yeah, I know I should use recursion here, but my head is totally a mess when dealing with this problem. Thanks, I'll study your answer through. – Zen Dec 02 '14 at 13:05