Knowee
Questions
Features
Study Tools

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.

🧐 Not the exact question you are looking for?Go ask a question

Solution

To define the function freq_dict(list1), we can follow these steps:

  1. Import the Counter class from the collections module.
  2. Define the function freq_dict that takes in a list list1 as a parameter.
  3. Inside the function, create a variable count_dict and set it equal to Counter(list1). This will create a dictionary where the keys are the elements from list1 and the values are the counts of each element.
  4. Return the count_dict from 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.

This problem has been solved

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

1/1

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.