I have been trying to add key values of a list into a dict whereas the key is the amount of times X is repeated in the list, and the value is X itself.
my_list = ["apple", "cherry", "apple", "potato", "tomato", "apple"]
my_grocery = {}
while True:
try:
prompt = input().upper().strip()
my_list.append(prompt)
except EOFError:
my_list_unique = sorted(list(set(my_list)))
for _ in my_list_unique:
my_grocery[my_list.count(_)] = _
#print(f'{my_list.count(_)} {_}')
print(my_grocery)
break
The expected output was:
{3: APPLE, 1: CHERRY, 1: POTATO, 1: TOMATO}
The the actual output received was:
{3: 'APPLE', 1: 'TOMATO'}
Does anyone have any idea why is that
you couldn't have duplicated keys in dict, in your case it's "1", you can use Counter for vise versa key-value savings occurrences of each product type
from collections import Counter
my_list = []
while True:
try:
prompt = input().strip()
if not prompt:
break
my_list.append(prompt)
except EOFError:
break
item_counts = Counter(my_list)
print(item_counts)
Counter({'tomato': 2, 'apple': 2, 'mango': 1})