VOOZH about

URL: https://www.geeksforgeeks.org/python/python-get-the-number-of-keys-with-given-value-n-in-dictionary/

⇱ Get the number of keys with given value N in dictionary - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Get the number of keys with given value N in dictionary - Python

Last Updated : 12 Jul, 2025

Our task is to count how many keys have a specific value n in a given dictionary. For example, in: data = {'a': 5, 'b': 3, 'c': 5, 'd': 7, 'e': 5} and n = 5. The keys 'a', 'c', and 'e' have the value 5 so the output should be 3.

Using Counter from collections

We count occurrences of each value using Counter and directly access n's count.


Output
3

Explanation:

  • Counter(d.values()) builds a frequency dictionary where each unique value in data becomes a key and its count becomes the value.
  • Direct Lookup with Counter()[n] allows quick access to how many times n appears, eliminating the need for iteration.

Using sum() with a Generator Expression

This method avoids creating extra lists by using a generator that yields 1 for each matching value then sum() efficiently counts these occurrences, making it faster and memory-efficient.


Output
3

Explanation:

  • data.values() extracts all values from the dictionary and the generator expression checks if v == n and yields 1 for each match.
  • sum() adds up these 1s giving the total count.

Using count() on values()

We directly use the count() method on data.values() to get the occurrences of n.


Output
3

Explanation:

  • data.values() extracts all values from the dictionary and list(data.values()) converts it into a list.
  • .count(n) counts occurrences of n in the list.

Using List Comprehension and len()

We iterate over the dictionary values filter the ones matching n and count them using len().


Output
3

Explanation: data.items() gives key-value pairs and list comprehension filters keys where v == n then len() counts the matching keys.

Comment