Get length of dictionary in Python

Dictionaries in Python are a collection of key-value pairs of data. These are used in many manipulations in Python and are one of the most important data structures in python. To calculate the length of the dictionary, the built-in len() method is used.

len() method in Python:

This in-built method takes a Python object as an argument and returns the number of items in it. It can be used on strings, lists, dictionaries, tuples, and sets. The only thing to note down is the argument must be either a sequence or a collection.

Finding length of a simple dictionary:



Consider the following details of a person :

Name:Steve
Age:30
Designation:Programmer

This information can be denoted by a simple dictionary. A simple dictionary contains just some key-value pairs. They are not much complex. When the len() method is applied, it directly gives the answer. It gives the number of entries in the dictionary. For example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to find 
# length of the dictionary
  
  
# a simple dictionary
dict1 ={'Name':'Steve', 'Age':30, 'Designation':'Programmer'}
  
# using len() counts the
# number of entries
print("len() method :", len(dict1))
  
# using dict.keys() counts
# the no.of.keys in dictionary
print("len() method with keys() :", len(dict1.keys()))
  
# using dict.values() counts
# the no.of.valuess in dictionary
print("len() method with values():", len(dict1.values()))

chevron_right


Output:

len() method : 3
len() method with keys() : 3
len() method with values(): 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

This kind of information can be represented using nested dictionaries. The nested dictionaries contain dictionaries within dictionaries. In a key-value pair, for a key, another dictionary can be the value. In such cases, if the dictionary is simply passed to the len() method, the output will not be correct. Look at the code below:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to find 
# length of the nested dictionary
  
  
# 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()))

chevron_right


Output:

len() method : 4
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 inner 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to find the
# length of the nested dictionary
  
  
# 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)

chevron_right


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.

isinstance() method:

This method takes two arguments. The first one is object. We need to pass a Python object to it. The object may be an int, a float, an iterable, or anything. The second argument to be passed is type/class. It denotes the type/class against which the first argument is checked for its instance. This method can help us find the length of a nested dictionary.

The idea is to first store the length of the whole dictionary in a variable (for 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. The sample code is given below.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to find
# length of nested dictionary
  
  
# 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)

chevron_right


Output:

The length of the dictionary is  9

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

Then modify the code as given below:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to find 
# length of nested dictionary
  
  
# 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'
           }       
      }
  
# 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):
          
        # add the length of inner dictionary
        length += len(i)
          
        # check whether th inner dictionary
        # is further nested
        for j in i.values():
              
             if isinstance(j, dict):
                length += len(j)
          
print("The total length of the dictionary is ", length)

chevron_right


Output:

The total length of the dictionary is  11


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.