How to Get the Dictionary Length in Python?

Python Dictionary is also referred to as associative arrays; this data structure stores the value in “key-value” pair format. Every key in the dictionary has a specific value, which can be accessed using the “key”.

Python dictionary length means how many keys are stored in a particular dictionary. This means that the number of ” key-value ” pairs in a dictionary determines its length.

This write-up will provide a detailed overview of how to get the dictionary length in Python. A discussion of the following aspects is provided in this article:

So, let’s begin this Python Guide!

How to Get the Dictionary Length in Python?

A dictionary is a type of data structure that is commonly used in Python for storing “key-value” pairs of data. The space dictionary occupies in memory is the length of the dictionary. Dictionary length is determined by the number of key-value pairs in the dictionary. The Python dictionary length is found using the “len()” function. The syntax of the “len()” function is shown below:

len(python_dictionary)

The “len()” function returns the length of the given Python dictionary in integer data type.

Example 1: Using len() Function to Get Python Dictionary Length

The inbuilt “len()” function returns the length of the Python dictionary. The following example demonstrates how “len()” function works:

Code:

#using len() Function
dict_value = {'Name': 'David', 'Age': 12};
dict_value1 = {'Name': 'Alex', 'Age': 12, 'Weight': 40};

print ('length of First Dictionary: ',len (dict_value))
print ('length of Second Dictionary: ',len (dict_value1))

In the mentioned code:

  • The above code creates two dictionaries i.e. dict_value and dict_value1.
  • The “len()” function takes the dictionary variable as an argument and returns the length of the dictionary.

Output:

The output shows the length of the given dictionaries.

Example 2: Using the len() Function to Get the Length of the Nested Dictionary

Calculate the length of the inner and outer dictionary using the len() function and then add them to find the total length. Let’s understand this concept via the following example:

Code:

# Using len() in Nested Dictionary
dict_value ={
    'Name':'Harry',     'Height':6.0,
    'Subjects':{'Math': 55,'Science':66, 'Physics':99}
        }
print('Length of Dictionary without Nested Dict: ',len(dict_value))

length_total = len(dict_value)+len(dict_value['Subjects'])
print("The total length including nested dictionary is:", length_total)

In the above code:

  • A nested dictionary is created in the above given program.
  • The “len()” function takes the dictionary variable “dict_value” as an argument and shows the length of the outer dictionary.
  • We accessed the nested dictionary using the key “Subjects” and passed it to the len() function to calculate the length of the inner/nested dictionary.
  • The total dictionary value will be the sum of the nested/inner dictionary and outer dictionary.

Output:

The output shows the length of the dictionary without a nested dictionary and with a nested dictionary.

Example 3: Using For Loop to Get the Length of Dictionary

The “for” loop, with the collaboration of the “isinstance()” function, is used to get the length of a dictionary. It will return the dictionary’s length, including nested dictionaries.

Code:

# Using For loop on Nested Dictionary
dict_value ={
    'Name':'Harry','Height':6.0,
    'Subjects':{'Math': 55,'Science':66,
    'Physics':99}
        }
length = len(dict_value)

for keys in dict_value.values():
        if isinstance(keys, dict):
            length += len(keys)

print("Total Dictionary Length: ", length)

Output:

In the above-given code:

  • A nested dictionary is created in the program.
  • The inbuilt “len()” function shows the length of the Python dictionary, excluding the nested/inner dictionary.
  • The “for loop” iterates on a dictionary variable named “dict_value”, and for all values of nested dictionary keys, the value will be added to the length of the outer dictionary.
  • The “isinstance()” function checks whether the specified value is a dictionary or not.
  • The len() function calculates the total dictionary length.

Output:

The output shows the length of the complete dictionary.

Note: this method is only recommended for simple nested dictionaries. For complex nested dictionaries, the upcoming method is preferred.

Example 4: Using Recursive Function to Get the Length of Dictionary

Recursive function means it calls itself continuously until the condition is not satisfied. The final result will return to the main program code when the input condition is fulfilled. The following example will illustrate how to get the dictionary length using the recursive function:

Code:

# Complex nested dictionary
dict_value ={'Students':{'BOYS':44,'GIRLS':24},
    'Report info':
        {'Marks Report':
         {'Pass': 54,'Fail':14},
        'City':'New York',
        'Country':'USA'
         },'Promote':54,
        }   def len_function(dict_value):
    length_dict = len(dict_value)
    for key, items in dict_value.items():
        if isinstance(items, dict):
            length_dict += len_function(items)
    return length_dict

print("Total Dictionary length including Nested Dict:",
    len_function(dict_value))

In the above code:

  • The dictionary values with nested dictionaries are initialized in the program.
  • The recursive function named “len_function” is initialized in the program.
  • The function has a “for” loop for iterating the dictionary value and “isinstance()” for checking whether the value is a dictionary or not. The dictionary length is calculated and returned to the function using the “return” statement.

Output:

This way, you can calculate the dictionary’s length using a recursive function.

That’s all from this guide!

Conclusion

In Python, the “len()” function, the “for loop with isinstance() function”, and the recursive function are used to calculate the dictionary’s length. Using these functions, the length of nested dictionaries can also be found. This post presented a detailed Python guide on how to find the dictionary’s length in Python with multiple examples.