Find a value from a dictionary in python by taking a key from user input [closed]

我是研究僧i 提交于 2021-02-11 15:51:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!