Home > other >  Using a key taken from an input and using it to recall a value
Using a key taken from an input and using it to recall a value

Time:07-16

The project is based on a cashier. When an input is accepted, it gets stored. I have used this to determine whether an item is in the dictionary or not. I am currently stuck on how to implement the input as a key to recall the corresponding value in a defined dictionary. Is there any way to do this using the tools I've used, or is a more complicated function required? My code is underneath, and the very last line seems to be the problem. Thanks.

my_dictionary = {"Chips", 1}

#Taking order

order = input("What do you want? \n")

#Recalling order

if order in my_dictionary:

print(f"Okay you want {order}")

else:

print("We dont have that please leave") exit()

#Gving price

print(my_dictionary["order"])

CodePudding user response:

Below is the code I have written that checks if the order the user inputs is:

  1. In your dictionary.
  2. In stock.

Python is case sensitive so I have added the .title() method to the user input to convert the string to title case. This is because the 'Chips' in your dictionary is also in title case.

my_dictionary = {
"Chips" : 1
}

order = input("What do you want?\n").title()

if order in my_dictionary:
    if my_dictionary[order] == 0:
        print("We don't have that, please leave.")
else:
        print(f"Okay you want, {order}")

Hopefully this helps :)

CodePudding user response:

remove the " " around order like: my_dictionary[order] in your last print() function.

  • Related