The problem set I am trying to solve: CS50P 2022 psets/3/grocery/
The code I wrote:
# Syntax of dict = {'key': value}
mydict = {}
# Infinite loop with break
while True:
try:
item = input().upper()
# Search if item matches a key inside the dict
if item in mydict:
mydict[item] = mydict[item] + 1
else:
mydict[item] = 1
except EOFError:
for i in mydict:
print(mydict[i], i)
break
The check50 results:
Results for cs50/problems/2022/python/grocery generated by check50 v3.3.7
:) grocery.py exists
:) input of EOF halts program
:) input of "apple" and "banana" yields "1 APPLE 1 BANANA"
:) input of "strawberry" and "strawberry" yields "2 STRAWBERRY"
:) input of "mango", "sugar", and "mango" yields "2 MANGO 1 SUGAR"
:( input of "tortilla" and "sweet potato" yields "1 SWEET POTATO 1 TORTILLA"
expected "1 SWEET POTATO...", not "\n\n1 TORTILLA..."
As you can see above, check50 is failing:
:( input of "tortilla" and "sweet potato" yields "1 SWEET POTATO 1 TORTILLA"
expected "1 SWEET POTATO...", not "\n\n1 TORTILLA..."
But when I run python grocery.py the result seems to match the expected outcome:
tortilla
sweet potato
1 TORTILLA
1 SWEET POTATO
I am having trouble understanding where I made the mistake. Please help.
My mistake was that the dict wasn't ordered properly. I solved that by importing OrderedDict method from collections class. Here's the code I added in the except statement:
from collections import OrderedDict
...
while True:
try:
...
except EOFError:
# https://docs.python.org/3/library/collections.html#collections.OrderedDict
mydict = OrderedDict(sorted(mydict.items(), key=lambda t: t[0]))
...