Error in the below program

typdict = {}

while True:
    try:
        food = input().upper()
        if food not in dict:
            dict[food] = 1
        else:
            dict[food] +=1
    except EOFError:
        break
    lst = sorted(dict.items())
    for k,v in lst:
        print(v,k)e or paste code here

Expected output should be, If i type mango and press enter then enter strawberry press enter,it should be display,
1 MANGO
1 STRAWBERRY.
but above program gives me the output, inputted mango and press enter its gives me 1 MANGO
help please

The above code you wrote doesn’t do anything other than give an error because you reference dict multiple times but have not defined before it is be referenced.

Once I change dict to the correct variable name, the code does not error out. However, it is not exactly clear what you are wanting the code to do. If I run the code and enter mango, it will print 1 MANGO to the terminal. Next, if I enter strawberry, then it will print the following to the terminal.

1 MANGO
1 STRAWBERRY

You stated:

Expected output should be, If i type mango and press enter then enter strawberry press enter,it should be display,
1 MANGO
1 STRAWBERRY

Well, that is what the code is displaying, so not sure what else you are expecting. Are you wanting a user to enter multiple foods and then have the list show after all the foods have been entered? If so, you will need to change your code to have some special entry to cause the while loop to exit and then you would execute the for loop outside the while loop. Currently, your while loop condition while True, so it will keep requesting input forever. Also, since your for loop is inside the while loop, it will keep printing the contents of the dictionary every iteration of the while loop.

1 Like

Thank you so much, i want enter mango and strawberry then i want the output
1 MANGO
1 STRAWBERRY, i try to change the code.

What does your new code look like?