[英]How can i print the elements of a dictionary if an input string matches with a key?
我有一本字典,其中的鍵是一些字符串,它們包含字符串值。 現在,我想編寫一個代碼,接受用戶輸入,如果輸入與任何鍵匹配,則打印鍵中包含的值。 如何訪問鍵中包含的元素並進行打印?
dict['key']
其中key是您的輸入字符串。 字典的工作原理類似於數組,除了數字以外,您可以使用字符串來獲取數據
您無需訪問字典中的鍵,只需使用用戶輸入作為鍵來打印值:
if user_input in your_dictionary :
print your_dictionary[user_input]
else :
print user_input, 'is not found in the dictionary'
(你需要if
檢查,以避免拋出Exception
的情況下,當你的用戶輸入是不是在你的字典)
您的程序應該是這樣的
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))
您還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')
請參閱此處的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.