Built with Tutify.io

    AIStudyLabs

    Python Dictionary len() Function

    Python Dictionary len() Function

    Python len() function is used to get the total length of the dictionary, this is equal to the number of items in the dictionary. len() function always returns the number of iterable items given in the Python dictionary. This method acts as a counter which is automatically defined the data. Dictionaries in Python are a collection of key-value pairs, this is one of the most important data structures in Python.

    Quick Examples Of Dictionary len()

    Following are the quick examples of the Python Dictionary len() function.

    
    # Example 1: Get the length of the dictionary using len()
    Technology={'course': 'python', 'fee': 4000, 'duration': '60 days', 'tutor': 'Richard'}
    Length=len(Technology)
    print("Length Of the dictionary:", Length)
    
    # Example 2:  Using keys() & len() get length of the keys
    print("length of the keys:", len(Technology.keys()))
    
    # Using values() & len() get length o f the values
    print("length of the values:", len(Technology.values()))
    
    # Example 3: get length of the empty dictionary
    Technology=dict()
    length=len(Technology)
    print("length of the technology:", length)
    

    1. Syntax of len() Function

    Following is the syntax of the len() function.

    
    # Syntax of the len()
    len(dict)
    

    1.1 Parameters of the len()

    The len() allows a single parameter which is iterable object.

    1.2 Return value of the len()

    len() function returns the number of iterable items given in the Python dictionary.

    2. Usage of the Python Dictionary len() Function

    len() is a function in Python that is used to get the number of elements (count) from a Dictionary. Let's create a dictionary and then find the length of the dictionary using the len() function.

    
    # Get the length of the dictionary using len()
    Technology={'course': 'python', 'fee': 4000, 'duration': '60 days', 'tutor': 'Richard'}
    length=len(Technology)
    print("Length Of the dictionary:", length)
    
    # Outputs:
    Length of the dictionary: 4
    

    2.2 Get the Length of keys and values of The Python Dictionary

    we can also get the length of keys present in the dictionary using the keys() with len() function. In addition, get the length of the values present in the dictionary by using the values() with len() function.

    Read the following articles to know more about keys() and values() methods.

    
    Technology={'course': 'python', 'fee': 4000, 'duration': '60 days', 'tutor': 'Richard'}
    # Using keys() & len() get length of the keys
    print("Length of the keys:", len(Technology.keys()))
    print("Length of the values:", len(Technology.values()))
    
    # Output:
    Length of the keys: 4
    Length of the values: 4
    

    3. Python Nested Dictionary Length Using len()

    The nested dictionaries contain dictionaries within dictionaries. In simple words, it refers to the dictionary, which consists of a set of multiple dictionaries. It is used to store the data in key-value pair, for a key, another dictionary can be the value. In such cases, using the len() function we can find the length of the Python nested dictionary.

    3.1 Get The Length of The Nested Dictionary

    
    # Find out the length of the nested dictionary
    Technology ={
                 'course': 'Python',
                 'fee':4000,
                 'discout':1000,
                 'duration':'45 days',
    	     'tutor':{'Name':'Richard','age':'50 years','experience':'20years'}		
    	        }
    
    # total length = length of outer dictionary +length of inner dictionary
    length = len(Technology)+len(Technology['tutor'])
    print("The length of the nested dictionary is: ", length)
    
    # Output:
    The length of the nested dictionary is:  8
    

    Is it clearly programmable to add length to internal dictionaries every time? What if we do not know in advance how many internal dictionaries there are? Let's do this programmatically.

    3.2 Get The Length of Nested Dictionary Programmatically

    When we take two inner dictionaries, the above method is not the correct way to add length to inner dictionaries every time. We can solve this problem by adding isinstance() with the len() method.

    isinstance() Method

    First, store the entire dictionary length in the variable name length. Then iterate through all the values() of the dictionary and find out whether it is an instance of dict. If it is true get the internal dictionary length and add it to the variable length. In this way, the total length of the group dictionary can be found. For example,

    
    Technology ={
                 'course': 'Python',
                 'fee':4000,
                 'discout':1000,
                 'duration':'45 days',
    	     'tutor':{'Name':'Richard','age':'50 years','experience':'20years'},
                 'timings':{'morning':'7a.m to 8a.m','evening':'6p.m to 7p.m'} 
                 }
    # Finding the outer dictionary length 
    length = len(Technology)
    # Finding all inner dictionaries length using iterate
    for i in Technology.values():
       # finding if the value is a dictionary
        if isinstance(i, dict):
            length += len(i)
    print("The length of the dictionary is:", length)
    
    # Outputs:
    The length of the dictionary is: 11
    

    Now let's see a little more complex nested dictionary and get the count.

    
    Technology ={
                 'course': 'Python',
                 'fee':4000,
                 'discount':1000,
                 'duration':'45 days',
    	      'tutor':{'Name':{'first name':'Richard','last name':'son'},
                         'age':'50 years','experience':'20years'},
                'timings':{'morning':'7a.m to 8a.m','evening':'6p.m to 7p.m'}   
    
                 }
    #Finding the outer dictionary length 
    length = len(Technology)
    # Finding all inner dictionaries length using iterate
    for x in Technology.values():
       # finding if the value is a dictionary
        if isinstance(x, dict):
             length += len(x)
             # Finding the length of innermost dictionary
             for y in x.values():
                 if isinstance(y, dict):
                     length +=len(y)
    print("The length of the dictionary is: ", length)
    
    # Outputs:
    The length of the dictionary is: 13
    

    4. Get Empty Python Dictionary Length

    We can find out the length of the empty dictionary in Python by using the len() function. In this example, we will create an empty dictionary and then find out the size of this dictionary.

    
    # get length of the empty dictionary
    Technology=dict()
    length=len(Technology)
    print("length of the technology:", length)
    
    # Output:
    length of the technology: 0
    

    5. Conclusion

    In this article, I have explained Python dictionary len() with examples. By using the len() function you can get the length of dictionaries as well nested dictionaries? And I have explained how to find out the length of the empty dictionary.

    Happy Learning !!

    <a id="h-related-articles"></a>

    Related Articles

    <a id="h-references"></a>

    References

    <a id="h-"></a>