[英]python dict values in elif loop
每次我輸入一個值時,代碼都會給我“訂閱”...如何獲取 dict 值?
Friends = {
'rolf' : 'blue',
'ronnie' : 'green',
'barbara' : 'purple',
'benny' : 'kaki',
'stewart' : 'yellow',
'mickey' : 'red'
}
def greetagain():
friend = input("Enter your friend name or color? ")
i = Friends.values()
if friend in Friends.keys():
print('yes it matches')
elif i in Friends.values():
print('ok ok')
else:
print('subscribe')
greetagain()
歡迎來到 SO。 請注意下面的更改,您使用不帶i
的變量朋友,因為您可以檢查朋友的值和鍵
def greetagain():
friend = input("Enter your friend name or color? ")
if friend in Friends.keys():
print('yes it matches')
elif friend in Friends.values():
print('ok ok')
else:
print('subscribe')
我只能理解你的問題的一部分,所以,我已經盡力解釋了。
if 條件已經可以正常工作了。 我認為您想在 elif 條件中檢索朋友(鍵)的名稱,為此您可以嘗試以下代碼:
Friends = { 'rolf' : 'blue', 'ronnie' : 'green', 'barbara' : 'purple', 'benny' : 'kaki', 'stewart' : 'yellow', 'mickey' : 'red' }
def greetagain():
friend = input("Enter your friend name or color? ")
if friend in Friends.keys():
print('Key matches')
print("Color associted to friend is:", Friends[friend])
elif friend in Friends.values():
for key, value in Friends.items():
if friend == value:
print('Color is present in list and associated by:', key)
else:
print('subscribe')
greetagain()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.