Python

Length of Dictionary Python

Python Dictionaries are a great way of having your Data in the form of key-value pairs, just like the JSON. However, becoming a good programmer requires you to be good in the optimization of your code and its working. To do this, the first step is to become aware of the size of the elements that you are using and the memory usage/storage they are consuming.

This post will act as your guide to finding the length of Python Dictionaries and will contain the following sections:

Method 1: Use the len() Method to Find the Length of Dictionary

The len() is a built-in method that is used to counter the length of various elements in Python. When this method is used to find the length of a Python Dictionary, it works as a counter and returns the total number of key-value pairs inside that Dictionary.

To demonstrate the use of the len() method in the case of Python Dictionary, take the following code:

dictVar = {"name": "John Doe", "Age":20, "Social": "LinuxHint"}
print(len(dictVar))

 

When this code is executed, it will show the length of the dictionary as:

As you can see, the len() method returns the number of key-value pairs in the dictionary, which is “3”.

Method 2: Use the len() Method to get the Length of a Nested Dictionary

If you are trying to apply the len() method on a nested list, then you will only get the number of non-nested key-value pairs. For example, take the following code:

dictVar={'people':
         {'John': 'Doe', 'Johny': 'Wick', 'Rudy': 'Smith'},
       'Food':
         {'Fast': 'Burger', 'FastFood': 'Ham', 'Steak': 'Medium'}}
print(len(dictVar))

 

Running this code will print the following result:

This answer is neither right nor wrong. If you talk about this “dictVar,” then it has two elements. However, if you were to talk about its nested elements, then it has more elements than 2. In such cases, you need to apply the len() method on each parent element and sum the result:

dictVar={'people':
         {'John': 'Doe', 'Johny': 'Wick', 'Rudy': 'Smith'},
       'Food':
         {'Fast': 'Burger', 'FastFood': 'Ham', 'Steak': 'Medium'}}
print(len(dictVar['people'])+len(dictVar['Food']))

 

This time around, when this program is executed, it will display the number of nested key-value pairs as:

As you can see, the number of nested key-value pairs is 6.

However, if you want to find the entire length of the dictionary, meaning the length of the parent dictionary and the nested dictionary, then simply use len() on the parent dictionary and add it:

dictVar={'people':
         {'John': 'Doe', 'Johny': 'Wick', 'Rudy': 'Smith'},
       'Food':
         {'Fast': 'Burger', 'FastFood': 'Ham', 'Steak': 'Medium'}}
print(len(dictVar)+len(dictVar['people'])+len(dictVar['Food']))

 

With this, the output is displayed as:

This output means that there are a total of 8 key-value pairs, nested and non-nested.

Method 3: Use the isinstance() Method to Get Entire Length of Nested Dictionary

To figure out the entire length of a dictionary, you can also utilize the isinstance() method along with the len() method. The isinstance() method checks whether the value in the first argument exists in the subclass.

To demonstrate the working of the isinstance() method to find the length of the dictionary, take the following code:

dictVar={'people':
         {'John': 'Doe', 'Johny': 'Wick', 'Rudy': 'Smith'},
       'Food':
         {'Fast': 'Burger', 'FastFood': 'Ham', 'Steak': 'Medium'}}

lengthVar = len(dictVar)
for a in dictVar.values():
    if isinstance(a, dict):
      lengthVar += len(a)
print("length of the dictionary is", lengthVar)

 

When this code is executed, it will produce the following outcome on the terminal:

The length of the dictionary is “8”.

Method 4: Use getsizeof() Method to Get the Memory Consumed by Dict

If you want to figure out the memory consumed by the dictionary in bytes, then you can utilize the getsizeof() method. However, to use this method you need to import the “sys” module.

To demonstrate the working of the getsizeof() method, use the following code snippet:

import sys
dictVar={'people':
         {'John': 'Doe', 'Johny': 'Wick', 'Rudy': 'Smith'},
       'Food':
         {'Fast': 'Burger', 'FastFood': 'Ham', 'Steak': 'Medium'}}

print(sys.getsizeof(dictVar))

 

This will print the following outcome on the terminal:

According to the output, the memory consumed by the dictionary “dictVar” is 184 bytes.

Conclusion

To find the length of a Dictionary variable in Python, the user can make use of the len() method, which is a built-in method. This method can also work for nested Dictionaries. However, in the case of nested Dictionaries, it will not return the count of key-value pairs of the nested dict but only of the parent dict. To get the memory consumption of the dictionary the user can utilize the getsizeof() method from the “sys” package.

About the author

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor's degree in computer science.