Home > Enterprise >  How can I compare the value in dictionary to the input value from users? python
How can I compare the value in dictionary to the input value from users? python

Time:10-30

I'm asking a user to input a number from the keyboard. For example users input 190, How can I compare 190 that user input to the value of the dictionary with the same value? is it equal or not?

This is my code:

my_dict = {'apple': [900, 190], 'orange': [1300, 90], 'pineapple': [550, 13], 'carrot': [600, 60], 'cucumber': [900, 30], 'egg plant': [1100, 20], 'zucchini': [1300, 10], 'garlic': [300, 70]}

for key, value in my_dict:
    usernumber = input('Input your number: ')
    if usernumber == value:
        print("Equal")
    else:
        print("Not equal")

For example, if users input the number 190, how can I check this value is in dictionary or not

CodePudding user response:

The best way to do this is to get all values in my_dict with my_dict.values(), then flatten that into one list of all the values (see this question for a variety of ways on how to flatten a list). Once you have a list of all the values in the dictionary, you can use a simply in comparison to check if the user's input is in that list.

Here's what I did:

my_dict = {'apple': [900, 190], 'orange': [1300, 90], 'pineapple': [550, 13], 'carrot': [600, 60], 'cucumber': [900, 30], 'egg plant': [1100, 20], 'zucchini': [1300, 10], 'garlic': [300, 70]}

usernumber = int(input('Input your number: '))
if usernumber in [num for elem in my_dict.values() for num in elem]:
    print("Equal")
else:
    print("Not equal")

Unlike the other answer, this will only output a single line, instead of many lines.

CodePudding user response:

Your code is correct, but since your values are list so instead of == you should do in check

my_dict = {'apple': [900, 190], 'orange': [1300, 90], 'pineapple': [550, 13], 'carrot': [600, 60], 'cucumber': [900, 30], 'egg plant': [1100, 20], 'zucchini': [1300, 10], 'garlic': [300, 70]}
usernumber = int(input('Input your number: ')) # Take input before and convert to int as well
if any(usernumber in (k:=val) for val in my_dict.values()):
    print("equal", k.index(usernumber))
else:
    print("unequal")

# output: equal 1
  • Related