繁体   English   中英

通过python 3.x中的字典循环列表

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM