2

I have a dictionary. How can I get the value by taking the key from user?

d = {'a': '1', 'b': '2', 'c':'3'}

If the user enters a I wanted to print value '1'.

roschach
  • 8,390
  • 14
  • 74
  • 124
Mikias Hundie
  • 107
  • 1
  • 2
  • 11
  • 1
    Possible duplicate of [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – l'L'l Apr 03 '19 at 00:34
  • 2
    What have you tried yourself? Do you know how to get user input? Do you know how to use a dictionary? – Loocid Apr 03 '19 at 00:34
  • yes I have tried it but I could not figure out how to search for the key and get the value – Mikias Hundie Apr 03 '19 at 00:38
  • 1
    `d[input()]` will do for a start. – gmds Apr 03 '19 at 00:51
  • @MikiasHundie You don't "search" for a key; Python does. You should always read the documentation or follow a tutorial first. – Selcuk Apr 03 '19 at 00:55

3 Answers3

3

This will do for you:

print(p["a"])

This prints the number for "a" in the dictionary.

For your program:

d = str(input("Enter what you want: "))
p  = {'a': '1', 'b': '2', 'c':'3'}
print(p[d])

If you enter a, then you get 1 as output.

Hope this Helps!!!!

1
user = input('enter a letter')
d = {'a': '1', 'b': '2', 'c':'3'}
for i in user:
    print(d[I])

use this method if your string consist of more then a single character

joanis
  • 10,635
  • 14
  • 30
  • 40
Kevin Mukuna
  • 149
  • 1
  • 6
1

Define your dictionary:

data = {'a': '1', 'b': '2', 'c':'3'}

Ask the user for the key using input():

key = input('Enter the key: ')

If the key is in the dictionary, print the value, otherwise print an error message:

if key in data:
    print('The value is:', data[key])
else:
    print('That key is not in the dictionary.')
John Gordon
  • 29,573
  • 7
  • 33
  • 58