How to find length of dictionary values? - GeeksforGeeks

10 May, 2020
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 Codeif __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 Codeif __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 Codeif __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 Codeif __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 codeif __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 Codeif __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 Codeif __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 Codeif __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
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python