Change language

Python | Find vocabulary depth

| |

The challenge is to find the depth of a given dictionary in Python. Let’s discuss all the different methods to accomplish this task.

Examples :

  Input:  {1: ’a’, 2 : {3: {4: {}}}}  Output:  4  Input:  {’a’: 1,’ b’: {’c’:’ geek’ }}  Output:  3 

Approach # 1: Naive Alpproach

The naive approach for determining the depth of a dictionary is to count the number of opening curly braces. But one of the drawbacks of this approach is that it will only work if you type correctly.

# Python3 Dictionary depth search program

def dict_depth (dic, level = 1 ):

 

str_dic = str (dic)

counter = 0

for i in str_dic: < / code>

if i = = "{" :

counter + = 1

return (counter)

  
# Driver code

dic = { 1 : ’ Geek’ , 2 : { 3 : { 4  : {}}}}

print (dict_depth (dic))

Exit:

 4 

Approach # 2 Using recursion

In this method we use recursion with the function max (), which selects the greatest depth for the current vocabulary, which is under scrutiny at every level.

# Python3 Depth Finder dictionary

def dict_depth (dic, level = 1 ):

 

if  not isinstance (dic, dict ) or not dic:

return level

return max ( dict_depth (dic [key], level + 1 )

for key in dic)

 
# Driver code

dic = { 1 : ’a’ , 2 : { 3 : { 4 : {}}}}

 

print (dict_depth (dic))

Exit:

 4 

Another version of the recursive solution is in using the

# Python3 Dictionary depth search program

def dict_depth (my _dict):

if isinstance (my_dict, dict ):

 

return 1 + ( max ( map (dict_depth, my_dict.values ​​()))

if my_dict else 0 )

  

return 0

  
# Driver code

my_dict = { 1 : ’a’ , 2 : { 3 : { 4 : {}}}}

print (dict_depth (my_dict))

Exit :

 4 

Approach # 3: iterative solution

With this approach, we store the nested key and its initial depth in a variable, say p_dict . Now run a loop for p_dict and continue with p_dict values ​​digging deeper into nested dictionaries.

# Python3 Program to search dictionary depth

def dict_depth (myDict):

 

Ddepth = 1

obj = [(k, Ddepth + 1 ) for k in myDict.values ​​()

if isinstance (k, dict )]

max_depth = 0

 

while (obj):

n, Ddepth = obj.pop ()

max_depth = max (max_depth, Ddepth)

 

  obj = obj + [(k, Ddepth + 1 ) for k in n.values ​​()

if isinstance (k, dict )]

 

return max_depth

 
# Driver code

myDict = { 1 : ’ a’ , 2 : { 3 : { 4 : {}}}}

print (dict_depth (myDict))

Exit:

 4 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically