w3resource

Python: Count the frequency in a given dictionary

Python dictionary: Exercise-61 with Solution

Write a Python program to count the frequency of a dictionary.

Visual Presentation:

Python Dictionary: Count the frequency in a given dictionary.

Sample Solution:

Python Code:

# Import the 'Counter' class from the 'collections' module.
from collections import Counter

# Define a function 'test' that takes a dictionary 'dictt' as an argument.
def test(dictt):
    # Use the 'Counter' class to count the frequency of values in the dictionary.
    result = Counter(dictt.values())
    
    # Return the result as a Counter object.
    return result

# Create a dictionary 'dictt' where the keys represent grades ('V', 'VI', etc.) and the values are integers.
dictt = {
    'V': 10,
    'VI': 10,
    'VII': 40,
    'VIII': 20,
    'IX': 70,
    'X': 80,
    'XI': 40,
    'XII': 20
}

# Print a message indicating the start of the code section and display the original dictionary.
print("\nOriginal Dictionary:")
print(dictt)

# Print a message indicating the purpose and generate a frequency count of values in the 'dictt' dictionary using the 'test' function.
print("\nCount the frequency of the said dictionary:")
print(test(dictt)) 

Sample Output:

Original Dictionary:
{'V': 10, 'VI': 10, 'VII': 40, 'VIII': 20, 'IX': 70, 'X': 80, 'XI': 40, 'XII': 20}

Count the frequency of the said dictionary:
Counter({10: 2, 40: 2, 20: 2, 70: 1, 80: 1})

Flowchart:

Flowchart: Count the frequency in a given dictionary.

Python Code Editor:

Previous: Write a Python program to find shortest list of values with the keys in a given dictionary
Next: Write a Python program to extract values from a given dictionaries and create a list of lists from those values.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/dictionary/python-data-type-dictionary-exercise-61.php