通过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”的方式来做。


FFIVE
浏览 137回答 3
3回答

SMILET

你可以试试这个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 SpaghettiPhil hasn't taken the pollJen likes PizzaBen hasn't taken the poll

开满天机

你的意思是喜欢for user in users:    try:        print('{} likes {}'.format(user, fav_food[user]))    except KeyError:        print("{} hasn't taken the poll".format(user))这将遍历所有用户,如果特定用户没有最喜欢的食物,那么它只会打印您所说的内容。

繁花如伊

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")像魅力一样工作,但值得记住的是,如果用户将空字符串作为他们最喜欢的食物,它会说他们没有参加投票
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python