To count the values by key in a Python dictionary, you can use comprehension to loop over the dictionary items, and then count the number of items for a given key with the Python len() function.

d = { "a":[1,2,3], "b":[1,2,3,4,5], "c":[1,2], "d":[1,2,3,4,5,6,7] }  

count = { k: len(v) for k, v in d.items() }

print(count)

#Output:
{'key1': 3, 'key2': 5, 'key3': 2, 'key4': 7}

In Python, dictionaries are a collection of key/value pairs separated by commas.

When working with dictionaries, sometimes we have keys which have values which are lists and we want to know the length of each of the lists for each key.

To count the values for each key in a dictionary using Python, we can use dictionary comprehension. With dictionary comprehension, we can loop over the key/value pairs and count the values for each key with len().

Below is a simple example which will count the values by key in a dictionary using Python.

d = { "a":[1,2,3], "b":[1,2,3,4,5], "c":[1,2], "d":[1,2,3,4,5,6,7] } 

count = { k: len(v) for k, v in d.items() }

print(count)

#Output:
{'a': 3, 'b': 5, 'c': 2, 'd': 7}

Using Python to Count Values by Key in Dictionary

The example above works if our dictionary is well structured and all of the keys have values of type list. If the values have mixed types, then using len() blindly might not give you the result you are looking for.

For example, if you have a dictionary where some values are lists and others are numbers, then you will want to only get the count of values for certain keys.

In this case, you can use an if statement to only return keys which have values of type list.

Let’s say we have the following dictionary.

d = { "a":[1,2,3], "b":2, "c":"Hello", "d":[1,2,3,4,5,6,7] } 

If you want to get the count of values for keys where the value is of type list, then you can use the following Python code.

d = { "a":[1,2,3], "b":2, "c":"Hello", "d":[1,2,3,4,5,6,7] }

count = { k: len(v) for k, v in d.items() if type(v) == list}

print(count)

#Output:
{'a': 3, 'd': 7}

Hopefully this article has been useful for you to learn how to count the values by key in a dictionary using Python.

Categorized in:

Python,

Last Update: March 22, 2024