Get length of dictionary in Python

14 Jan, 2020
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.
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:
# Python program to find # length of the dictionary    # a simple dictionarydict1 ={'Name':'Steve', 'Age':30, 'Designation':'Programmer'}  # using len() counts the# number of entriesprint("len() method :", len(dict1))  # using dict.keys() counts# the no.of.keys in dictionaryprint("len() method with keys() :", len(dict1.keys()))  # using dict.values() counts# the no.of.valuess in dictionaryprint("len() method with values():", len(dict1.values()))
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:
# Python program to find # length of the nested dictionary    # A nested dictionarydict2 ={ # 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 : 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:
# 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 dictlength = 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.
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.
# Python program to find# length of nested dictionary    # nested dictionarydict2 ={       '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 dictionariesfor 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

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:
# Python program to find # length of nested dictionary    # nested dictionarydict2 ={       '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 dictionariesfor 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)
Output:
The total length of the dictionary is  11

python-dict
Python
Technical Scripter
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python