128k views
2 votes
Define a function below called count candy. The function takes a single argument of type list of strings. Each string in the list is the name of a candy. Complete the function so that it returns a dictionary of key: value pairs, where each key is a string that is the name of a candy and the count is how often that candy appears in the list.

1 Answer

4 votes

Final answer:

The count_candy function in Python takes a list of candy names and computes a dictionary that maps each candy name to its respective count within the list.

Step-by-step explanation:

Python Function: count_candy

To define the function count_candy that counts the occurrences of each candy in a list and returns a dictionary with this information, you can follow these steps:

  1. Create a new empty dictionary called candy_count.
  2. Iterate over the list of candies.
  3. For each candy, increase its count in the candy_count dictionary or set it to 1 if it's not there yet.
  4. Return the candy_count dictionary.

Here is the code for the function:

def count_candy(candy_list):
candy_count = {}
for candy in candy_list:
if candy in candy_count:
candy_count[candy] += 1
else:
candy_count[candy] = 1
return candy_count

This function will effectively count and display the number of times each type of candy appears in the input list.

User Dan Inactive
by
7.2k points

No related questions found

Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.