[英]How do I input an item from a dictionary and return its definition?
x = input("Color: ")
list = [
{"Color": "Red", "Mood": "Angry"},
{"Color": "Blue", "Mood": "Sad"},
{"Color": "Green", "Mood": "Jealous"}
]
for mood in list: #???
print (mood["Mood"]) #???`
如果我提示用戶輸入顏色,我希望它只在字典中打印與該顏色相關的“情緒”。 上面的 for 循環是我能想到的,但無論用戶輸入哪種顏色,它都會打印所有情緒“憤怒”、“悲傷”、“嫉妒”。
我只是在學習,並且使用“for”循環從這里卡住到 go 的位置。 (我知道我可以為每種顏色/情緒組合制作幾個 boolean 表達式,但我正在練習使用字典,所以這是首選方法)”
您應該真正改變組織數據的方式。 計算以 colors 為鍵、情緒為項的字典:
l = [
{"Color": "Red", "Mood": "Angry"},
{"Color": "Blue", "Mood": "Sad"},
{"Color": "Green", "Mood": "Jealous"}
]
moods = {d['Color']: d['Mood'] for d in l}
# {'Red': 'Angry', 'Blue': 'Sad', 'Green': 'Jealous'}
然后,不需要循環:
print(moods.get(input('Color: '), 'unknown color!'))
好的,讓我們看看你的代碼做了什么
x = input("Color: ")
這會向用戶詢問顏色並將其分配給變量“x”。
list = [
{"Color": "Red", "Mood": "Angry"},
{"Color": "Blue", "Mood": "Sad"},
{"Color": "Green", "Mood": "Jealous"}
]
這使得列表包含三個獨立的字典 - 一個具有“顏色”“紅色”和“情緒”“憤怒”,第二個具有“顏色”“藍色”和“情緒”“悲傷”等等。
for mood in list: #???
這將遍歷列表中的所有條目,因此每次循環運行循環變量“mood”將是上面的字典之一。
print (mood["Mood"]) #???`
這將打印當前字典的“情緒”值。
所以,您的問題是您從不檢查“顏色”是否為 x!
最簡單的解決方法可能是在 for 循環中進行檢查:
for item in list: # it's not a "mood", we have the full dictionary
if item["Color"] == x:
print(item["Mood"])
# if we know the color will only be in the list once,
# we can break out of the loop
break
有更簡潔的方法來做同樣的事情,比如列表推導式,它可以像 for-loop 那樣在一行中進行過濾,比如
moods = [ it["Mood"] for it in list if it["Color"] == x ]
但這些都是更高級的主題。
您也可能只是想以不同的方式組織數據,例如,您可以只使用“顏色”值作為字典鍵並使用單個字典:
colors_to_moods = {
"Red": "Angry",
"Blue": "Sad",
"Green": "Jealous"
}
print(colors_to_moods[x])
您要使用哪一個取決於您要對程序執行的操作。
如果您想堅持使用當前列表,可以測試x
:
x = input("Color: ")
color_to_mood = [
{"Color": "Red", "Mood": "Angry"},
{"Color": "Blue", "Mood": "Sad"},
{"Color": "Green", "Mood": "Jealous"}
]
for c2m in color_to_mood:
if x == c2m['Color']:
print (c2m["Mood"])
最好使用這樣的字典:
x = input('color: ')
colors = {
'red' : 'angry',
'green' : 'jealous',
'blue' : 'sad'
}
print ('your mood is: ',colors[x])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.