Define the function freq_dict(list1) that counts the occurrence of each element from a list and returns a dictionary to show the count of each element.Example:list1 = [11, 45, 8, 11, 23, 45, 23, 45, 89]Expected Output:{11: 2, 45: 3, 8: 1, 23: 2, 89: 1}Hint:Counter from the collections module is a dict subclass which helps to count hashable objects.
Question
Define the function freq_dict(list1) that counts the occurrence of each element from a list and returns a dictionary to show the count of each element.Example:list1 = [11, 45, 8, 11, 23, 45, 23, 45, 89]Expected Output:{11: 2, 45: 3, 8: 1, 23: 2, 89: 1}Hint:Counter from the collections module is a dict subclass which helps to count hashable objects.
Solution
To define the function freq_dict(list1), we can follow these steps:
- Import the
Counterclass from thecollectionsmodule. - Define the function
freq_dictthat takes in a listlist1as a parameter. - Inside the function, create a variable
count_dictand set it equal toCounter(list1). This will create a dictionary where the keys are the elements fromlist1and the values are the counts of each element. - Return the
count_dictfrom the function.
Here is the code implementation:
from collections import Counter
def freq_dict(list1):
count_dict = Counter(list1)
return count_dict
Now, if we call the function with the example list list1 = [11, 45, 8, 11, 23, 45, 23, 45, 89], it will return the expected output:
list1 = [11, 45, 8, 11, 23, 45, 23, 45, 89]
print(freq_dict(list1))
Output:
{11: 2, 45: 3, 8: 1, 23: 2, 89: 1}
The Counter class is a convenient way to count the occurrences of elements in a list and create a dictionary with the counts.
Similar Questions
Define a function count_occurrence(list1). The function iterates a given list and count the occurrence of each element and create a dictionary to show the count of each element.Examplelist1 = [11, 45, 8, 11, 23, 45, 23, 45, 89]Expected output:{11: 2, 45: 3, 8: 1, 23: 2, 89: 1}
Write a Python program to get a dictionary value from the user and count the number of keys that are having the same value and print the count.
A Counter turns a sequence of values into a defaultdict(int)-like object mappingkeys to counts:
Which of the following command is used to find the number of entries in the given dictionary? dic = {"course":"Python", "year":2021}dic.size()len(dic)size(dic)dic.len()
Suppose d = {“john”:40, “peter”:45}. To obtain the number of entries in dictionary which command do we use?d.size()len(d)size(d)d.len()
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.