0

I'm trying to check if a given word by the user is a key in my dictionary but the response always goes to the 'else' part instead.

This is my dic:

mydic = {'Paris':[132,34] 'Rome':[42,35] 'San Remo':[23,66]}

This is the code:

my_input = input('Write a command').lower()
useful_input = my_input.split()


if my_input == 'info':
        print("Write 'city' and city name to get the info")
            
elif their_command == 'city' and phrase:
    if phrase in mydic.keys():
        print(f"{phrase} city has {mydic.get(phrase)[0]} churches.")
    else:
        print('Wrong')

So I need to search if the second word (or second and third word) after the word 'city', which is the command, is a key in my dictionary. If it is, I need to return the key's first value in the print statement. With my code, it goes straight to the 'else' and prints 'wrong', so why is this happening?

dazai
  • 766
  • 4
  • 25
  • You forced the input words to lower case - maybe you should do the same for your dictionary keys. You might have spotted this problem f you had introduced a temporary `print(phrase)` statement. – Joffan Apr 24 '21 at 13:40

3 Answers3

1

You convert your input to lower case.

Your keys are mixed case.

By the way, you can write phrase in mydic, you don't need to get the list of keys. And you can look up in a dictionary as mydic[phrase]. The only difference between that method and get is the handling of a nonexistent entry.

something
  • 174
  • 4
1

I think because your input is lowercased. Try the code below

mydic = {'Paris':[132,34], 'Rome':[42,35], 'San Remo':[23,66]}

my_input = input('Write a command: ')
useful_input = my_input.split()
their_command = useful_input[0]
words = useful_input[1:]
phrase = " ".join(words)

if my_input.lower() == 'info':
        print("Write 'city' and city name to get the info")
            
elif their_command.lower() == 'city' and phrase:
    if phrase in mydic.keys():
        print(f"{phrase} city has {mydic.get(phrase)[0]} churches.")
    else:
        print('Wrong')
Ken
  • 33
  • 5
0

phrase = second and third argument joined (from first example of code phrase = ''.join(words)), so if you type 'city Paris Rome' in input

on line

if phrase in mydic.keys():

Python will compare if parisrome in the key values of dictionary which always will be false at least you have parisrome city in mydic

My suggestions is not join strings, but iterate throw dictionary with items from useful_input list

Amazing examples, iteration throw dictionary you can find here Iterating over dictionaries using 'for' loops

Mykola Rudenko
  • 196
  • 2
  • 9