Computer Science
Predict the output:
fruit = {}
L1 = ['Apple', 'banana', 'apple']
for index in L1 :
if index in fruit:
fruit[index] += 1
else :
fruit[index] = 1
print(len(fruit))
print(fruit)
Python Dictionaries
26 Likes
Answer
Output
3
{'Apple': 1, 'banana': 1, 'apple': 1}
Explanation
This python program counts the frequency of each fruit in a list and outputs the number of unique fruits and their frequency. The program does not account for the case sensitivity of the fruit names so "Apple" and "apple" are counted as separate fruits. Here is a step-by-step explanation of the program:
- Initialize the variables
- The
fruitvariable is a dictionary that stores the frequency of each fruit. - The
L1variable stores the input list ['Apple', 'banana', 'apple'].
- The
- Loop through each fruit
indexin the list L1- If the fruit already exists as a key in the
fruitdictionary, its value is incremented by 1. - If the fruit is not in the
fruitdictionary, a new key is added with a value of 1.
- If the fruit already exists as a key in the
- The length of the
fruitdictionary is printed to the console, indicating the number of unique fruits. - The
fruitdictionary is printed to the console, showing the frequency of each fruit.
Answered By
2 Likes
Related Questions
Find the errors:
text = "abracadbra" counts = {} for word in text : counts[word] = counts[word] + 1my_dict = {} my_dict[(1,2,4)] = 8 my_dict[[4,2,1]] = 10 print(my_dict)Predict the output:
arr = {} arr[1] = 1 arr['1'] = 2 arr[1] += 1 sum = 0 for k in arr: sum += arr[k] print(sum)Predict the output
a = {(1,2):1,(2,3):2} print(a[1,2])