Reputation: 177
I have a dictionary where the keys are some strings and they hold string values. Now I want to write a code which takes input from the user and if the input matches with any of the keys, prints the value contained in the keys. How do I access the elements contained in the keys and print them?
Upvotes: 0
Views: 1266
Reputation: 8811
You can also get
function of python dictionaries like this
my_dict = {1: 'One', 2:'Two', 3:'Three'}
my_key = input("Enter your key")
print my_dict.get(my_key,'Key not found')
See the examples here.
Upvotes: 0
Reputation: 23556
You don't need to access keys in your dictionary, just print the value, using your user input as key:
if user_input in your_dictionary :
print your_dictionary[user_input]
else :
print user_input, 'is not found in the dictionary'
(you need if
check to avoid throwing an Exception
in case when your user input is not in your dictionary)
Upvotes: 2
Reputation: 3465
Your program should be something like this
a_dict = {'a': 100, 'b': 200, 'c': 300}
key = input('what key: ')
if key in a_dict:
print('the value of key {} is {}'.format(key, a_dict[key]))
else:
print('key {} is not in the dict'.format(key))
Upvotes: 0
Reputation: 2750
dict['key']
where key is your input string. A dictionary works like an array except rather than numbers you can use a string to get to the data
Upvotes: 1