Python - Creating Dictionaries by reading text files and searching through that dictionary
You are close. There's no need to iterate your dictionary. The beauty of dict
is it offers O(1) access to values given a key. You can just take your input and feed the key to your dictionary:
search = input("Enter state name:") #user enters input of state
print(d.get(search), "is the State Flower for", search)
With Python 3.6+, you can write this more clearly using f-strings:
print(f'{d.get(search)} is the State Flower for {search}')
If the state doesn't exist in your dictionary d.get(search)
will return None
. If you don't want to print anything in this situation, you can use an if
statement:
search = input("Enter state name:") #user enters input of state
if search in d:
print(f'{d[search]} is the State Flower for {search}')