Skip to content

Instantly share code, notes, and snippets.

@ArthurDelannoyazerty
Last active May 22, 2024 09:57
Show Gist options
  • Select an option

  • Save ArthurDelannoyazerty/6b616e5b77ab448db2413451a9e2e594 to your computer and use it in GitHub Desktop.

Select an option

Save ArthurDelannoyazerty/6b616e5b77ab448db2413451a9e2e594 to your computer and use it in GitHub Desktop.
Count the number of final elements in a dict. This function works for nested dict. Each final value is stored in a list.
def count_leaves_dict(element:dict) -> int:
if isinstance(element, list): return len(element)
if not isinstance(element, dict): raise Exception("Wrong data type")
nb_leaves = 0
for _, value in element.items():
nb_leaves += count_leaves_dict(value)
return nb_leaves
@ArthurDelannoyazerty

Copy link
Copy Markdown
Author

Example of a good dict :

d = {
    'a' : [1,2,3,4],
    'b' : {
        'ba':[5,6,7], 
        'bb':[8,9]
        }
}

Result = 9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment