[英]looping a list through a dictionary in python 3.x
我意識到還有其他與此類似的問題,但我不太明白。
假設有一本字典:
fav_food = {'jen':'pizza','eric':'burrito','jason':'spaghetti','tom':'mac'}
然后有一個列表:
users = ['jason', 'phil', 'jen', 'ben']
這里的情況是
if a user in the list 'users' is in the dict. 'fav_food.keys()',
then print(the user + " likes" + fav_food[the user])
if a user in the list 'users' is not in the dict. 'fav_food.keys()',
then print(the user + " hasn't taken the poll")
回報應該是:
Jason likes Spaghetti
Phil hasn't taken the poll
Jen likes Pizza
Ben hasn't taken the poll
我想使用“ for”循環,並以某種方式遍歷字典...但是無論我做什么,我都會不斷出錯。
如果可能的話,我寧願以最“ Python”的方式來做。
非常感謝您的幫助!
你的意思是像
for user in users:
try:
print('{} likes {}'.format(user, fav_food[user]))
except KeyError:
print("{} hasn't taken the poll".format(user))
這將遍歷所有用戶,如果特定用戶沒有最喜歡的食物 ,那么它只會打印您所說的內容。
你可以試試這個
for user in users:
if user in fav_food.keys():
print(user.capitalize(),"likes",fav_food[user].capitalize())
else:
print(user.capitalize(),"hasn't taken the poll")
這將輸出為-
Jason likes Spaghetti
Phil hasn't taken the poll
Jen likes Pizza
Ben hasn't taken the poll
fav_food = {'jen':'pizza','eric':'burrito','jason':'spaghetti','tom':'mac'}
users = ['jason', 'phil', 'jen', 'ben']
for user in users:
print(f"{user} likes {fav_food[user]}" if fav_food.get(user, None) else f"{user} hasn't taken the poll yet")
就像魅力一樣工作,但要記住,如果用戶將空字符串作為自己喜歡的食物,它會說他們沒有參加調查
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.