![]() |
VOOZH | about |
Python provides multiple methods to get the length, and we can apply these methods to both simple and nested dictionaries. Let’s explore the various methods.
To calculate the length of a dictionary, we can use Python built-in len() method. It method returns the number of keys in dictionary.
3
Let's explore other methods of getting length of a dictionary in python:
Table of Content
Another less common method is to use a list comprehension, which can also be used to count the number of keys in a dictionary.
Example:
3
Explanation:
We can also use the sum() function to count the number of items in a dictionary by adding 1 for each key-value pair.
Example:
3
When working with nested dictionaries, we may want to count only the top-level keys or count the keys in nested dictionaries. If we want to get the length of the top-level dictionary, len() works just as it does with simple dictionaries.
3
Explanation:
Another method to count items in a dictionary, including nested dictionaries, is using a loop. For nested dictionaries, we can manually iterate through all the nested keys and values.
9
Explanation:
We can also use the len() function on the dictionary’s keys, values or items to determine the number of keys, values or key-value pairs.
3 3 3