[英]Python: How to use a dictionary to call methods (values in dictionary) to run based on user input (key in dictionary) in a different function?
[英]How to receive user input for Dictionary function in Python?
我正在嘗試創建國家及其首都的字典,但是只能從用戶輸入中創建。 密鑰將是國家/地區名稱, 值將是大寫字母,因此它看起來像這樣:
capital_dict = {"France":"Paris", "Germany":"Berlin", "Japan:"Tokyo"}
我如何做到這一點,以便用戶輸入所需的信息並由口譯員從中創建字典?
感謝您的幫助,謝謝
您可以for
input
使用簡單的for
循環:
capital_dict = {}
while True:
country = input('Enter country name: ')
capital = input('Enter capital name: ')
if not (country and capital):
break
capital_dict[country] = capital # or capital_dict.update({country: capital})
如果用戶為任何組合輸入了country
和capital
的空字符串,則循環將中斷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.