To calculate the length of a dictionary, we can use the Python built-in len() method. The len() method returns the number of keys in a Python dictionary.
Python Dict len() Syntax
Syntax: len(Dict)
Return: It returns an integer which is the length of the string.
Name:Steve Age:30 Designation:Programmer
Basic example of finding the length of a dictionary
Python3
dict1 = { 'Name' : 'Steve' , 'Age' : 30 , 'Designation' : 'Programmer' } print ( "Dictionary:" , dict1) print ( "Length of dictionary:" , len (dict1)) |
Output:
Dictionary: {'Name': 'Steve', 'Age': 30, 'Designation': 'Programmer'} Length of dictionary: 3
Finding length of nested dictionary
Consider the following details about a person:
Name:Steve Age:30 Designation:Programmer address: Street:Brigade Road City:Bangalore Country:India
Problem when trying to find length of nested dictionary:
Python3
# A nested dictionary dict2 = { # outer dictionary 'Name' : 'Steve' , 'Age' : 30 , 'Designation' : 'Programmer' , 'address' : { # inner dictionary 'Street' : 'Brigade Road' , 'City' : 'Bangalore' , 'Country' : 'India' } } print ( "len() method :" , len (dict2)) print ( "len() method with keys() :" , len (dict2.keys())) print ( "len() method with values():" , len (dict2.values())) |
Output:
len() method with keys() : 4
len() method with values(): 4
Here, whichever method you apply, You will get only ‘4’ as the output. But the actual number of entries is ‘7’. The keys are name, age, designation, address, street, city, and country. The method considers the outer dictionary which is a value for one of the keys as a single value.
To overcome this problem, we need to explicitly add the length of the inner dictionary to the outer one. It can be coded as given below:
Python3
# A nested dictionary dict2 = { 'Name' : 'Steve' , 'Age' : 30 , 'Designation' : 'Programmer' , 'address' : { 'Street' : 'Brigade Road' , 'City' : 'Bangalore' , 'Country' : 'India' } } # total length = length of outer dict + # length of inner dict length = len (dict2) + len (dict2[ 'address' ]) print ( "The length of the nested dictionary is:" , length) |
Output:
The length of the nested dictionary is: 7
Now it works fine!!! However, is it possible to explicitly program to add the length of inner dictionaries every time? What if we do not know in prior how many inner dictionaries are there? Now consider the following detail:
Name: first name:Steve last name:Jobs Age:30 Designation:Programmer address: Street:Brigade Road City:Bangalore Country:India
Here we have two inner dictionaries. It is not an optimized way to explicitly add the length of the inner dictionaries every time. We can solve this problem by combining isinstance() with len() method. The idea is to first store the length of the whole dictionary in a variable (say ‘length’ here). Then iterate through all the values()of the dictionary and check whether it is an instance of dict. If ‘True’ then the length of that inner dictionary is found and added to the variable length. In this way, the total length of a nested dictionary could be found.
Example 1: Finding length of nested dictionary dynamically using for-loop:
When we have more keys in a dictionary whose values are again dictionaries. Then we need to check if the type of the value of each key, if it’s a dictionary, then we use len() on the value and add the value to the length of the outer dictionary.
Python3
# nested dictionary dict2 = { 'Name' : { 'first_name' : 'Steve' , 'Last_name' : 'Jobs' }, 'Age' : 30 , 'Designation' : 'Programmer' , 'address' : { 'Street' : 'Rockins Road' , 'City' : 'Bangalore' , 'Country' : 'India' } } # storing the outer dictionary length length = len (dict2) # iterating to find the length # of all inner dictionaries for i in dict2.values(): # checking whether the value is a dictionary if isinstance (i, dict ): length + = len (i) print ( "The length of the dictionary is" , length) |
Output:
The length of the dictionary is 9
Note: This approach will only work when the nesting of the dictionaries is only upto 2 levels.
If the dictionary is further deeply nested like below:
Name: first name:Steve last name:Jobs Age:30 Designation:Programmer address: Street: St_number:4 St_name:Brigade Road City:Bangalore Country:India
Example 2: Using Recursion to find length of nested dictionary:
Here we have used a recursive function count_nested_len() to count the length of each dictionary, we iterate on the keys of dictionaries, as soon as a value is a dictionary, we recuse on that dictionary.
Python3
# nested dictionary dict2 = { 'Name' : { 'first_name' : 'Steve' , 'Last_name' : 'Jobs' }, 'Age' : 30 , 'Designation' : 'Programmer' , 'address' : { 'Street' : { 'st_number' : 4 , 'st_name' : 'Rockins Road' }, 'City' : 'Bangalore' , 'Country' : 'India' } } # we use recursive function to count # length of nested dictionaries def count_nested_len(d): length = len (d) for key, value in d.items(): if isinstance (value, dict ): length + = count_nested_len(value) return length print ( "Nested dictionary length:" , count_nested_len(dict2)) |
Output:
Nested dictionary length: 11
Approach 3 : Using Dictionary Comprehension
Python3
# nested dictionary
dict2 ={
‘Name’:
{
‘first_name’:’Steve’,
‘Last_name’:’Jobs’
},
‘Age’:30,
‘Designation’:’Programmer’,
‘address’:
{
‘Street’:
{
‘st_number’:4,
‘st_name’:’Rockins Road’
},
‘City’:’Bangalore’,
‘Country’:’India’
}
}
# Using dictionary comprehension to find the length of the nested dictionary
length = len({k: v for k, v in dict2.items()})
print(“The length of the dictionary is”, length)
#This code is contributed by Edula Vinay Kumar Reddy
METHOD 4:Using a generator expression with sum() function.
APPROACH:
A generator expression is used to create a sequence of 1’s, where each 1 corresponds to a key in the dictionary. The sum() function is then used to add up the 1’s, which gives the length of the dictionary.
ALGORITHM:
1.Create a generator expression that generates a sequence of 1’s for each key in the dictionary.
2.Use the sum() function to add up the 1’s in the sequence.
3.Return the sum, which represents the length of the dictionary.
Python3
dict1 = { 'Name' : 'Steve' , 'Age' : 30 , 'Designation' : 'Programmer' } length = sum ( 1 for key in dict1) print (length) |
3
The time complexity of this approach is O(n), where n is the number of keys in the dictionary.
The space complexity of this approach is O(1)