Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding key pair values into a dict missing

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

like image 465
Camilo170299 Avatar asked Sep 08 '26 15:09

Camilo170299


1 Answers

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

like image 57
Anna Andreeva Rogotulka Avatar answered Sep 11 '26 05:09

Anna Andreeva Rogotulka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!