Python | Count keys with particular value in dictionary - GeeksforGeeks (2024)

Last Updated : 15 May, 2023

Improve

Sometimes, while working with Python dictionaries, we can come across a problem in which we have a particular value, and we need to find frequency if it’s occurrence. Let’s discuss certain ways in which this problem can be solved.

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

Python3

# Python3 code to demonstrate working of

# Count keys with particular value in dictionary

# Using loop

# Initialize dictionary

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

# printing original dictionary

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

# Initialize value

K = 2

# Using loop

# Selective key values in dictionary

res = 0

for key in test_dict:

if test_dict[key] == K:

res = res + 1

# printing result

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

Output

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

Time Complexity: O(n)
Auxiliary Space: O(1)

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

Python3

# Python3 code to demonstrate working of

# Count keys with particular value in dictionary

# Using sum() + values()

# Initialize dictionary

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

# printing original dictionary

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

# Initialize value

K = 2

# Using sum() + values()

# Selective key values in dictionary

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

# printing result

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

Output

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

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #3 : Using count() and values().These methods can be used together to find number of keys with particular value.

Python3

# Python3 code to demonstrate working of

# Count keys with particular value in dictionary

# Using count() + values()

# Initialize dictionary

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

# printing original dictionary

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

# Initialize value

K = 2

# Using count() + values()

list1=list(test_dict.values())

# Selective key values in dictionary

res = list1.count(K)

# printing result

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

Output

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

Time Complexity: O(n)
Auxiliary Space : O(n)

Method #4: Using lambda functions

Python3

# Python3 code to demonstrate working of

# Count keys with particular value in dictionary

# Initialize dictionary

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

# printing original dictionary

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

# Initialize value

K = 2

keys = list(test_dict.keys())

res = len(list(filter(lambda x: test_dict[x] == K, keys)))

# printing result

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

Output

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

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #5: Using collections.Counter()

Python3

# Python3 code to demonstrate working of

# Count keys with particular value in dictionary

# Using collections.Counter()

# Importing collections for Counter

import collections

# Initialize dictionary

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

# printing original dictionary

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

# Initialize value

K = 2

# Using collections.Counter()

res = collections.Counter(test_dict.values())[K]

# printing result

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

#This code is contributed by Edula Vinay Kumar Reddy

Output

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

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #6: Using operator.countOf() method:

Python3

# Python3 code to demonstrate working of

# Count keys with particular value in dictionary

import operator as op

# Initialize dictionary

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

# printing original dictionary

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

# Initialize value

K = 2

# Using count() + values()

list1=list(test_dict.values())

# Selective key values in dictionary

res = op.countOf(list1,K)

# printing result

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

Output

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

Time Complexity: O(N)
Auxiliary Space: O(N)

Method 7: Using a dictionary comprehension

Step-by-step approach:

  • Create a new dictionary using a dictionary comprehension that counts the occurrence of values in the original dictionary.
  • Create another dictionary using a dictionary comprehension that counts the occurrence of keys with a particular value in the original dictionary.
  • Access the value of the key equal to the given value K in the second dictionary to get the frequency

Python3

# Initialize dictionary

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

# Initialize value

K = 2

# Create a new dictionary with count of values as keys

count_dict = {v: list(test_dict.values()).count(v) for v in set(test_dict.values())}

# Create a new dictionary with count of keys with particular value as values

freq_dict = {v: sum(1 for k in test_dict.keys() if test_dict[k] == v) for v in count_dict.keys()}

# Access the frequency of K

res = freq_dict[K]

# printing result

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

Output

Frequency of K is : 3

Time complexity: O(n^2)
Auxiliary space: O(n)



manjeet_04

Improve

Next Article

Python | Get key with maximum value in Dictionary

Please Login to comment...

Python | Count keys with particular value in dictionary - GeeksforGeeks (2024)

FAQs

How to get the key of a certain value in dictionary Python? ›

Get keys from a dictionary by value in Python
  1. d = {'key1': 1, 'key2': 2, 'key3': 3} print(list(d)) # ['key1', 'key2', 'key3'] source: dict_keys_values_items.py. ...
  2. key = [k for k, v in d. items() if v == 'aaa'][0] print(key) # key1 key = [k for k, v in d. ...
  3. def get_keys_from_value(d, val): return [k for k, v in d.
Aug 20, 2023

How to extract value of particular key from dictionary in Python? ›

Step-by-step approach:
  1. Initialize dictionary.
  2. Create two empty variables, key and val.
  3. Use a for loop to iterate over the dictionary and assign the key-value pairs to the variables key and val respectively.
  4. Print the result.
Apr 26, 2023

How to check how many values a key has in a dictionary in Python? ›

To determine how many items (key-value pairs) a dictionary has, use the len() method.

How do you access the value associated with a specific key in a dictionary? ›

You can access the values in the dictionary by using the [] brackets or the get() method. If the specified key is absent in the dictionary, it returns a default value. However, when we use dict[key], the interpreter raises a KeyError exception.

How to get specific key-value from list of dictionary in Python? ›

Step-by-step approach:
  1. Create a list test_list containing dictionaries with key-value pairs.
  2. Use list comprehension to create a new list res.
  3. For each dictionary d in test_list, check if the key 'gfg' is in the dictionary.
  4. If the key 'gfg' is in the dictionary, get its value and append it to the list res.
May 16, 2023

How to print value of a particular key in dictionary in Python? ›

Python dictionary is collection of key value pairs. Value associated with a certain key is returned by get() method. You can also obtain value by using key inside square brackets.

How do you check if a key has a specific value in Python? ›

Here's the step-by-step approach:
  1. Initialize the dictionary.
  2. Print the original dictionary.
  3. Use the dictionary's get() method with a default value of None to check if the key has a non-None value.
  4. If the value returned by get() is not None, set the result to True, else False.
  5. Print the result.
Apr 17, 2023

How to check if a key-value exists in a list of dictionary Python? ›

Let's get started.
  1. Method 1: Using the in Operator. You can use the in operator to check if a key exists in a dictionary. ...
  2. Method 2: Using the dict. get() Method. ...
  3. Method 3: Using Exception Handling. Exception handling allows you to first try and access the value of the key and handle the KeyError exception if it occurs.
Jun 27, 2023

How to check keys and values in dictionary Python? ›

Looking up a value which is not in the dict throws a KeyError -- use "in" to check if the key is in the dict, or use dict. get(key) which returns the value or None if the key is not present (or get(key, not-found) allows you to specify what value to return in the not-found case).

How to get specific key-value from nested dictionary in Python? ›

Here are the steps:
  1. Initialize an empty list to store the values of the particular key.
  2. Iterate over each value in the dictionary using a for loop.
  3. Check if the particular key exists in the current value using an if condition.
  4. If the key exists, append its value to the list initialized in step 1.
Apr 28, 2023

How to get particular key-value from array of objects in Python? ›

Let's discuss certain ways in which this problem can be solved.
  1. Method #1: Using list comprehension.
  2. Method #2: Using map() + get()
  3. Method #3 : Using keys(),values() and index() methods.
  4. Method 4: using a simple for loop and a conditional statement.
  5. Approach:
Apr 27, 2023

How to get only the values from a dictionary in Python? ›

To fetch the values associated with the keys in a dictionary, Python dictionary values() method This method is used to retrieve all the values so we know what kind of information is stored. The Python dictionary values() method returns an object that only contains all the values in a dictionary.

How to find a key in a dictionary in Python? ›

How to Check if a Key Exists in a Dictionary in Python – Python Dict Has Key
  1. Method 1: Using the in Operator. You can use the in operator to check if a key exists in a dictionary. ...
  2. Method 2: Using the dict. get() Method. ...
  3. Method 3: Using Exception Handling.
Jun 27, 2023

How to get only the key from dictionary in Python? ›

Dictionaries have no order.

But you can get just the keys from a dictionary with the . keys() method.

How to find the value of a key? ›

get() method. We can get the value of a specified key from a dictionary by using the get() method of the dictionary without throwing an error, if the key does not exist. As the first argument, specify the key. If the key exists, the corresponding value is returned; otherwise, None is returned.

Top Articles
Latest Posts
Article information

Author: Greg O'Connell

Last Updated:

Views: 5696

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.