简体   繁体   English

如果输入字符串与键匹配,如何打印字典的元素?

[英]How can i print the elements of a dictionary if an input string matches with a key?

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? 如何访问键中包含的元素并进行打印?

dict['key']

where key is your input string. 其中key是您的输入字符串。 A dictionary works like an array except rather than numbers you can use a string to get to the data 字典的工作原理类似于数组,除了数字以外,您可以使用字符串来获取数据

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) (你需要if检查,以避免抛出Exception的情况下,当你的用户输入是不是在你的字典)

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))

You can also get function of python dictionaries like this 您还get像这样get python词典的功能

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 . 请参阅此处的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM