问题
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'
.
回答1:
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!!!!
回答2:
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.')
回答3:
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
来源:https://stackoverflow.com/questions/55485344/find-a-value-from-a-dictionary-in-python-by-taking-a-key-from-user-input