Get the length of Dictionary Values in Python

avatar

Borislav Hadzhiev

Tue Jun 14 20222 min read

Get the length of Dictionary Values in Python #

To get the length of a dictionary value:

  1. Access the dictionary at the specific key, e.g. my_dict['name']
  2. Pass the value to the len() function, e.g. len(my_dict['name'])
  3. The len() function returns the number of items of an object
main.py
my_dict = {'name': 'Alice', 'tasks': ['dev', 'test', 'ship']} # 👇️ get the length of a specific value print(len(my_dict['tasks'])) # 👉️ 3 # 👇️ get the length of the entire dictionary print(len(my_dict)) # 👉️ 2

The len() function returns the length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

The first example shows how to get the length of the value that corresponds to the tasks key in the dictionary.

The second example shows how to get the number of key-value pairs in the dictionary.

You can also create a new dictionary that maps the specific keys to the length of their values.

main.py
my_dict = {'name': 'Alice', 'tasks': ['dev', 'test']} len_values = {key: len((value)) for key, value in my_dict.items()} print(len_values) # 👉️ {'name': 5, 'tasks': 2} print(len_values['tasks']) # 👉️ 2

The name key has a value of length 5 and the tasks key has a value of length 2.

Note that this approach only works if all values in the dictionary can be passed to the len() function.

You can use the same approach to create a new dictionary that only contains key-value pairs where the value is of specific type.

main.py
my_dict = { 'name': 'Alice', 'tasks': ['dev', 'test', 'ship'], 'languages': ['python'] } # 👇️ only get length for list values len_values = {key: len((value)) for key, value in my_dict.items() if isinstance(value, list)} print(len_values) # 👉️ {'tasks': 3, 'languages': 1} print(len_values['languages']) # 👉️ 1

The new dictionary only contains key-value pairs for values that are of type list.

You could also use the str, tuple, set and any other class that can be passed to the len function.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

If you need to sum the length of all dictionary values, use the sum() function.

main.py
my_dict = { 'tasks': ['dev', 'test', 'ship'], 'languages': ['python'] } total_values_len = sum(len(val) for val in my_dict.values()) print(total_values_len) # 👉️ 4

The example sums the length of all of the list values in the dictionary.

The sum function takes an iterable, sums its items from left to right and returns the total.

The dict.values method returns a new view of the dictionary's values.

main.py
my_dict = {'id': 1, 'name': 'Alice'} print(my_dict.values()) # 👉️ dict_values([1, 'Alice'])
Use the search field on my Home Page to filter through my more than 1,000 articles.