[英]Trying to print dictionary values in python
我正在嘗試編寫一個簡單的程序,要求輸入喜歡的彩虹色首字母(ROYGBIV)並打印給定字母的值。 例如,如果用戶輸入為“ R”,則程序將打印“紅色”。 我嘗試使用字典,但無法正常工作。 你能幫我糾正我的錯誤嗎?
def rainbow():
color = {
"R", "Red"
"O", "Orange"
"Y", "Yellow"
"G", "Green"
"B", "Blue"
"I", "Indigo"
"V", "Violet"
}
userint = input("Enter first letter of fav color: ").upper()
if userint in color:
print color.get(userint,"none")
else:
print("no match")
rainbow()`
有了它, color
當前是一個Python 集 ,如下所示:
{'BlueI', 'GreenB', 'IndigoV', 'OrangeY', 'R', 'RedO', 'Violet', 'YellowG'}
對於鍵/值對,構造字典的語法需要冒號而不是逗號:
可以通過將用逗號分隔的鍵:值對列表放在大括號中來創建字典,例如:
{'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}
,或通過dict()
構造函數。
在您的情況下,這將是:
color = {
"R": "Red",
"O": "Orange",
"Y": "Yellow",
"G": "Green",
"B": "Blue",
"I": "Indigo",
"V": "Violet"
}
另外,您可以使用字典理解:
color = {c[0]: c for c in
{'Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'}}
最后,如果您對“ Green”和“ B”(以及其他)為何混在一起感到好奇,那是因為Python的字符串文字串聯 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.