Python

Length of Dictionary Python

In this post, we’ll find out various ways to calculate the dictionary length in Python. The size of a dictionary can refer to its length or the amount of memory space it takes up. For the calculation of the number of elements in a dictionary, make use of the len() function. The sys module’s getsizeof() method can also be used to calculate the size of a dictionary in bytes. The len() function of Python is often used to calculate the size/length of objects. Given this method, a dictionary object returns the dictionary’s size which is the number of key-value pairs it contains in our case.

What are Dictionaries in Python?

Dictionaries are collections of key-value pairs as defined in Python. These are some of the most essential data structures in Python and are utilized in numerous manipulations. It’s as simple as putting items inside curly braces and separating them with commas to make a dictionary. A key and a value are stated as a pair for each item (key: value). Keys must be unique and the type should be immutable, however, values can be of any data type and can be repeated (string, integer, or tuple with immutable members).

The built-in len() method is used to determine the dictionary’s length. This built-in method receives a Python object as an argument and returns the number of elements contained within it. The only thing to keep in mind is that the argument must be a sequence or a collection.

Example 1:

Using the built-in function len(), we can quickly determine the length of a Python dictionary. This function returns the number of lengths that are stored in the dictionary as key-value pairs. The number of iterable elements in the dictionary is always returned by the len() function. This technique works as a counter, defining the data for you automatically.

Let’s look at an example of how to use the len() method to determine the length of a dictionary. Below we have given the screenshot of the example code.

dict_leng = {"Alex":10,"Peter":40,"Harry":60}

print("Length of dictionary is",len(dict_leng))

The length of the dictionary is 3, as you can see below.

Example 2:

Another example is utilizing Python’s instance() method to determine the length of a dictionary. Two parameters are passed to the instance method. The object is the first argument. As an argument, you must know that it is crucial to provide an object. A float, integer, or even string can be used for this purpose. The class/type parameter is the second argument. This method will assist the user in determining the size of a dictionary.

In this example, we’ll first construct a variable called “student_length.” We may iterate through all of the specified values that are present in the dictionary to see if it is an instance of the dictionary.

new_dict={
       'Student_info':
           {
               'student_name':'Peter',
               'T_name':'Alex'
           },
       'student_age':30,
       'student_position':'Topper',
       'addr':
           {
           'student_City':'Los Angeles',
           'Country':'U.S.A'
           }      
      }
student_length = len(new_dict)
for a in new_dict.values():
    if isinstance(a, dict):
student_length += len(a)
print("length of the dictionary is", student_length)

The following is a screenshot attached which shows the result when we run the given code.

Example 3:

Now, we’ll talk about the length of values in a Python dictionary. Have a look at how you can use a Python dictionary to find out the length of values. In this case, we can simply use the list comprehension approach to determine the length of dictionary items. As an argument, it is important to provide an object. The item could be a float, integer, or something else entirely.

def main():
new_dict = {'nu_list':[3, 6, 8],
           'nu_tupple':(8, 6, 5),
           'intg':7,
           'str_nu':"Revert",
           }
    num = sum([1 if isinstance(new_dict[a], (str, int))
                 else len(new_dict[a])
                 for a in new_dict])
print("Length of values:", num)
if __name__ == '__main__':
main()

The following is the result of the code attached above as you can see.

Example 4:

Another illustration of determining the length of dictionary values is given here. We can find out how to use the dict.items() method to discover the length of values in a dictionary. This method returns the list and determines the dictionary’s number of values. This procedure does not have any parameters. Let’s look at an example (given below) of how to estimate the length of values using dict.items().

def main():

new_dict = {'new_list':[8, 7, 6,2],
           'new_tupple':(2, 3, 4, 6),
           'int_value':3,
           'new_str':"Revert"
           }

count_num = 0

    for n_key, n_val in new_dict.items():

        if isinstance(n_val, int):
count_num += 1

elifisinstance(n_val, str):
count_num += 1

        else:
count_num += len(n_val)
print(" total length of value:", count_num)
if __name__ == '__main__':
main()

The following screenshot shows the output after the implementation of the above code.

Example 5:

The length of keys in a Python dictionary will be discussed in this example. Now, let’s figure out how you can determine the length of the keys in a dictionary. In this example, the method len() can be used to measure the keys length in a dictionary. The quantity of iterable items in an object is returned by this function. We may also count the numbers using the len() and the keys() function. Take a look at this illustration to see how to get the keys length in a dictionary.

my_dict = {'A':3,'b':5,'c':6}

x = len(my_dict.keys())

print("Length of keys:",x)

Here is the generated output.

Example 6:

A nested dictionary is built in the same way that a regular dictionary is. The primary distinction is that each value is a separate dictionary. Let’s explore how you can determine the length of a nested dictionary in an easy way. Using Python’s various capabilities, we can count the elements in this nested dictionary in this example.

dict={'names':
         {'ALex': 'Peter', 'Harry': 'Shawn', 'Lipa': 'Tailor'},
       'Foods':
         {'Toast': 'Burger', 'Mutton': 'chicken', 'Milk': 'Jam'}}
a = len(dict)
b = len(dict['names'])+len(dict['Foods'])
print("Length of the Nested dictionary is",b)

Below, you can observe the outcome of the code attached above.

Example 7:

In our final example of the article, we’ll learn how to determine the length of an empty dictionary in Python. For the purpose of finding the length of an empty dictionary, the len() method of Python can be used. In this example, we’ll make an empty dictionary and calculate its length.

dict_new = {}

dic_length = len(dict_new)

print('Empty dictionary Length:', dic_length)

The following screenshot shows the outcome of how the given code is executed.

Conclusion

We learned how to use the len() method to find the length of a Python Dictionary in this Python tutorial. With the help of well-detailed examples, we’ve also discussed numerous ways to do so. It is highly recommended to use these examples at your end and gain practical knowledge.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content