Open In App

Get length of dictionary in Python

Last Updated : 19 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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)


Output

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)



Previous Article
Next Article

Similar Reads

Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Convert String Dictionary to Dictionary Python
Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of the dictionary, in string format to a dictionary. Let's discuss certain ways in which this can be done. Convert String Dictionary to Dictionary Using json.loads() This task ca
6 min read
Python | Dictionary initialization with common dictionary
Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a dictionary with records values, so that they can be altered later. This kind of application can occur in cases of memoizations in general or competitive programming. Let’s discuss certain way in which this task can be performed. Method 1: Using zip
7 min read
Python - Update dictionary with other dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the update of dictionary with other keys of dictionary. This can have applications in domains in which we need to add certain records to previously captured records. Let's discuss certain ways in which this task can be performed. Method #1 : Using loo
9 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python - Replace dictionary value from other dictionary
Given two dictionaries, update the values from other dictionary if key is present in other dictionary. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}, updict = {"Geeks" : 10, "Best" : 17} Output : {'Gfg': 5, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 10} Explanation : "Geeks" and "Best" values updated to 10 and 17. Inpu
6 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 min read
Practice Tags :
three90RightbarBannerImg