Python | Counting keys with a specific value in a dictionary



Method # 1: Using a loop
This problem can be solved using the naive looping method. In this, we simply iterate over each key in the dictionary, and when a match is found, the counter increments.

# Python3 code to demonstrate how it works
# Number of keys with a specific value in the dictionary
# Using a loop

 
# Initialize dictionary

test_dict = { `gfg` : 1 , `is` : 2 , `best` : 3 , < code class = "string"> `for` : 2 , `CS` : 2 }

  
# print original dictionary

print ( "The original dictionary:" +   str (test_dict))

 
# Initialize value

K = 2

 
# Using a loop
# Selected key values ​​in the dictionary

res  = 0

for key in test_dict:

if test_dict [key] = = K:

res = res + 1

 
# print result

print ( "Frequency of K is: " + str (res))

Output:

< blockquote>

The original dictionary: {`gfg`: 1, `CS`: 2, `best`: 3, `for`: 2, `is`: 2}
Frequency of K is: 3

Method # 2: Using sum () + values ​​()
This can also be solved using the combination sum () and value () . In this case, the sum is used to perform the summation of the filtered values, and the dictionary values ​​are retrieved using values()

# Python3 code to demonstrate how it works
# Number of keys with a specific value in the dictionary
# Using sum () + values ​​()

 
# Initialize dictionary

test_dict = { `gfg` : 1 , `is` : 2 , `best` : 3 , `for` : 2 , `CS` : 2 }

  
# print the original dictionary

print ( "The original dictionary:" +   str (test_dict))

 
# Initialize value

K = 2

 
# Using sum () + values ​​()
# Choice actual key values ​​in the dictionary

res = sum (x = = K for x in test_dict.values ​​())

 
# print result

print ( "Frequency of K is : " + str (res))

Output:

The original dictionary: {` gfg `: 1,` CS `: 2,` best `: 3,` for `: 2,` is`: 2}
Frequency of K is: 3