Last active
May 22, 2024 09:57
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example of a good dict :
Result = 9