Friday, December 27, 2024
Google search engine
HomeLanguagesHow to find length of dictionary values?

How to find length of dictionary values?

In Python, Dictionary is a collection of unordered data values. Dictionaries are also changeable and indexed. Dictionary holds key:value pair and they are written inside curly brackets. Each key:value pair maps the key to its associated value.

Here we use isinstance() method to check the type of the value whether it is a list, int, str, tuple, etc. isinstance() method which is an inbuilt method in Python. It returns a boolean if the object passed is an instance of the given class or not.

Let’s discuss different methods to find the length of dictionary values.

Note: In the below methods the length of the string value is takes as one.

Method #1 Using in operator

Example: 1




# Python program to find the 
# length of dictionary values
  
  
def main():
      
    # Defining the dictionary
    dict1 = {'a':[1, 2, 3],
             'b'🙁1, 2, 3),
             'c':5,
             'd':"nopqrs",
             'e':["A", "B", "C"]}
  
    # Initialize count 
    count = 0
  
    # using in operator 
    for k in dict1:
          
        # Check the type of value 
        # is int or not
        if isinstance(dict1[k], int):
            count += 1
  
        # Check the type of value 
        # is str or not
        elif isinstance(dict1[k], str):
            count += 1
        else:
            count += len(dict1[k])
              
    print("The total length of value is:", count)
      
  
# Driver Code
if __name__ == '__main__':
    main()


Output:

The total length of value is: 11

Example :2




# Python program to find the
# length of dictionary values
  
def main():
      
    # Defining the dictionary
    dict1 = {'A':"abcd",
             'B':set([1, 2, 3]), 
             'C'🙁12, "number"), 
             'D':[1, 2, 4, 5, 5, 5]}
  
    # Create a empty dictionary
    dict2 = {}
  
    # using in operator
    for k in dict1:
          
        # Check the type of value
        # is int or not
        if isinstance(dict1[k], int):
            dict2[k] = 1
  
        # Check the type of value 
        # is str or not
        elif isinstance(dict1[k], str):
            dict2[k] = 1
              
        else:
            dict2[k] = len(dict1[k])
              
    print("The length of values associated\
    with their keys are:", dict2)
    print("The length of value associated\
    with key 'B' is:", dict2['B'])
  
      
# Driver Code
if __name__ == '__main__':
    main()


Output:

The length of values associated with their keys are: {‘A’: 1, ‘B’: 3, ‘C’: 2, ‘D’: 6}
The length of value associated with key ‘B’ is: 3

Method #2 Using list comprehension




# Python program to find the 
# length of dictionary values
  
  
def main():
      
    # Defining the dictionary
    dict1 = {'a':[1, 2, 3],
           'b'🙁1, 2, 3),
           'c':5,
           'd':"nopqrs",
           'e':["A", "B", "C"]}
  
    # using list comprehension
    count = sum([1 if isinstance(dict1[k], (str, int))
                 else len(dict1[k]) 
                 for k in dict1])
      
    print("The total length of values is:", count)
  
      
# Driver Code
if __name__ == '__main__':
    main()


Output:

The total length of values is: 11

Method #3 Using dictionary Comprehension




# Python program to find the 
# length of dictionary values
  
  
def main():
      
    # Defining the dictionary
    dict1 = {'A': "abcd",
             'B': set([1, 2, 3]),
             'C': (12, "number"),
             'D': [1, 2, 4, 5, 5, 5]}
  
    # using dictionary comprehension
    dict2 = {k:1 if isinstance(dict1[k], (str, int)) 
             else len(dict1[k])
             for k in dict1}
      
    print("The length of values associated \
    with their keys are:", dict2)
    print("The length of value associated \
    with key 'B' is:", dict2['B'])
  
      
# Driver Code
if __name__ == '__main__':
    main()


Output:

The length of values associated with their keys are: {‘A’: 1, ‘B’: 3, ‘C’: 2, ‘D’: 6}
The length of value associated with key ‘B’ is: 3

Method #4 Using dict.items()

Example :1




# Python program to find the
# length of dictionary values
  
def main():
    # Defining the dictionary
    dict1 = {'a':[1, 2, 3], 
             'b'🙁1, 2, 3), 
             'c':5,
             'd':"nopqrs",
             'e':["A", "B", "C"]}
  
    # Initialize count 
    count = 0
  
    # using dict.items()
    for key, val in dict1.items():
          
        # Check the type of value 
        # is int or not
        if isinstance(val, int):
            count += 1
  
        # Check the type of value
        # is str or not
        elif isinstance(val, str):
            count += 1
              
        else:
            count += len(val)
    print("The total length of value is:", count)
  
      
# Driver code
if __name__ == '__main__':
    main()


Output:

The total length of values is: 11

Example :2




# Python program to find the
# length of dictionary values
  
def main():
    # Defining the dictionary
    dict1 = {'A': "abcd"
             'B': set([1, 2, 3]), 
             'C': (12, "number"),
             'D': [1, 2, 4, 5, 5, 5]}
  
    # Create a empty dictionary
    dict2 = {}
  
    # using dict.items()
    for key, val in dict1.items():
          
        # Check the type of value 
        # is int or not
        if isinstance(val, int):
            dict2[key] = 1
  
        # Check the type of value
        # is str or not
        elif isinstance(val, str):
            dict2[key] = 1
              
        else:
            dict2[key] = len(val)
  
    print("The length of values associated \
    with their keys are:", dict2)
      
    print("The length of value associated \
    with key 'B' is:", dict2['B'])
  
  
# Driver Code
if __name__ == '__main__':
    main()


Output:

The length of values associated with their keys are: {‘A’: 1, ‘B’: 3, ‘C’: 2, ‘D’: 6}
The length of value associated with key ‘B’ is: 3

Method #5 Using enumerate()

Example :1




# Python program to find the
# length of dictionary values
  
def main():
      
    # Defining the dictionary
    dict1 = {'a':[1, 2, 3], 
             'b'🙁1, 2, 3),
             'c':5,
             'd':"nopqrs",
             'e':["A", "B", "C"]}
  
    # Initialize count 
    count = 0
  
    # using enumerate()
    for k in enumerate(dict1.items()):
          
        # Check the type of value 
        # is int or not
        if isinstance(k[1][1], int):
            count += 1
  
        # Check the type of value 
        # is str or not
        elif isinstance(k[1][1], str):
            count += 1
              
        else:
            count += len(k[1][1])
              
    print("The total length of value is:", count)
  
      
# Driver Code
if __name__ == '__main__':
    main()


Output:

The total length of value is: 11

Example :2




# Python program to find the
# length of dictionary values
  
def main():
      
    # Defining the dictionary
    dict1 = {'A': "abcd",
             'B': set([1, 2, 3]), 
             'C': (12, "number"), 
             'D': [1, 2, 4, 5, 5, 5]}
  
    # Create a empty dictionary
    dict2 = {}
  
    # using enumerate()
    for k in enumerate(dict1.items()):
          
        # Check the type of value 
        # is int or not
        if isinstance(k[1][1], int):
            dict2[k[1][0]] = 1
  
        # Check the type of value 
        # is str or not
        elif isinstance(k[1][1], str):
            dict2[k[1][0]] = 1
              
        else:
            dict2[k[1][0]] = len(k[1][1])
  
    print("The length of values associated\
    with their keys are:", dict2)
      
    print("The length of value associated \
    with key 'B' is:", dict2['B'])
      
      
# Driver Code
if __name__ == '__main__':
    main()


Output:

The length of values associated with their keys are: {‘A’: 1, ‘B’: 3, ‘C’: 2, ‘D’: 6}
The length of value associated with key ‘B’ is: 3

RELATED ARTICLES

Most Popular

Recent Comments