Counting Values for Key in Dictionary

Write a Python function to count the number of values associated with a specific key in a dictionary. Return the count.

Example 1:

Input: {"a": [1, 2, 3], "b": [4, 5]}, "a" 
Output: 3

Example 2:

Input: {"x": [10, 20, 30, 40], "y": [50, 60]}, "x" 
Output: 4

Access the dictionary value (which should be a list) using the key and use the len function to find the number of elements in the list.

def count_values(dict, key):
return len(dict[key])

© Let’s Data Science


Unlock AI & Data Science treasures. Log in!