Open In App

How to find length of dictionary values?

Last Updated : 10 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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



Similar Reads

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 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
Python - Filter dictionary values in heterogeneous dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to filter out certain values based on certain conditions on a particular type, e.g all values smaller than K. This task becomes complex when dictionary values can be heterogeneous. This kind of problem can have applications across many domains. Let's discuss c
6 min read
Python - Split Dictionary values on size limit of values
Given a dictionary with string values, the task is to write a python program to split values if the size of string exceeds K. Input : {1 : "Geeksforgeeks", 2 : "best for", 3 : "all geeks"}, limit = 5Output : {1: 'Geeks', 2: 'forge', 3: 'eks', 4: 'best ', 5: 'for', 6: 'all g', 7: 'eeks'}Explanation : All string values are capped till length 5. New v
8 min read
Python - Extract Unique values dictionary values
Sometimes, while working with data, we can have problem in which we need to perform the extraction of only unique values from dictionary values list. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Extract Unique values dictionary values Using sorted() + set comprehen
7 min read
Python - Remove duplicate values across Dictionary Values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the duplicate values across all the dictionary value lists. This problem can have applications in data domains and web development domains. Let's discuss certain ways in which this task can be performed. Input: test_dict = {'Manjeet': [1], 'Akash
8 min read
Python - Test for Even values dictionary values lists
Given a dictionary with lists as values, map Boolean values depending upon all values in List are Even or not. Input : {"Gfg" : [6, 8, 10], "is" : [8, 10, 12, 16], "Best" : [10, 16, 14, 6]} Output : {'Gfg': True, 'is': True, 'Best': True} Explanation : All lists have even numbers. Input : {"Gfg" : [6, 5, 10], "is" : [8, 10, 11, 16], "Best" : [10, 1
8 min read
Different ways of sorting Dictionary by Values and Reverse sorting by values
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, 10 different ways of sorting the Python dictionary by values and also reverse s
17 min read
Python - Dictionary values String Length Summation
Sometimes, while working with Python dictionaries we can have problem in which we need to perform the summation of all the string lengths which as present as dictionary values. This can have application in many domains such as web development and day-day programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using s
4 min read
How to Fix: Length of values does not match length of index
In this article we will fix the error: The length of values does not match the length of the index in Python. Cases of this error occurrence: C/C++ Code # importing pandas import pandas as pd sepal_length = [5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9] sepal_width = [4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.1, 5.2, 5.3] petal_length = [3.3, 4.6, 4
2 min read
Article Tags :
Practice Tags :