Open In App

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

Last Updated : 07 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Python
from collections import Counter

d = {'a': 5, 'b': 3, 'c': 5, 'd': 7, 'e': 5}
n = 5

res = Counter(d.values())[n]

print(res)

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.

Python
d = {'a': 5, 'b': 3, 'c': 5, 'd': 7, 'e': 5}
N = 5

res = sum(1 for v in d.values() if v == n)

print(res)  

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.

Python
d = {'a': 5, 'b': 3, 'c': 5, 'd': 7, 'e': 5}
n = 5

res = list(d.values()).count(n)

print(res)  

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().

Python
d = {'a': 5, 'b': 3, 'c': 5, 'd': 7, 'e': 5}
n = 5

res = len([k for k, v in d.items() if v == n])

print(res) 

Output
3

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



Next Article
Practice Tags :

Similar Reads