i need to build a function that return me the depth of a dictonary. for example :
dict_depth({1:"a",2:"b"})
depth = 0
dict_depth({1: {1:"a",2:"b"},2:"b"})
depth = 1
dict_depth({1: {1:"a",2:"b"},2: {1:{1:"a",2:"b"},2:"b"}})
depth = 2
but i need to add another condition where if the function get a non dict value the function will return me a string that say ("this is not a dict") insted of typeError. but as you can see i cant think of a way to do it with my function because even if the function get a dict value at the end because of the Recursion the function will get a non dict value.
what do you think may fix the problem? thank you guys
-this is my code, it does work
def dict_depth(d):
if isinstance(d, dict):
if not d:
return 1
else:
return 1 + max(dict_depth(value) for value in d.values())
else:
return -1