简体   繁体   English

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

[英]looping a list through a dictionary in python 3.x

I realize there are other questions similar to this, but I'm not quite getting it. 我意识到还有其他与此类似的问题,但我不太明白。

Let's say there's a dictionary: 假设有一本字典:

fav_food = {'jen':'pizza','eric':'burrito','jason':'spaghetti','tom':'mac'}  

and then there's a list: 然后有一个列表:

users = ['jason', 'phil', 'jen', 'ben']  

The scenario here is that 这里的情况是

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")

the return should be: 回报应该是:

Jason likes Spaghetti  
Phil hasn't taken the poll  
Jen likes Pizza  
Ben hasn't taken the poll  

I wanted to use the loop 'for' and somehow iterate a list through a dictionary... but I keep getting error no matter what I do. 我想使用“ for”循环,并以某种方式遍历字典...但是无论我做什么,我都会不断出错。
I'd prefer to do it the most "Python" way, if possible. 如果可能的话,我宁愿以最“ Python”的方式来做。

I'd appreciate the help! 非常感谢您的帮助!

You mean like 你的意思是像

for user in users:
    try:
        print('{} likes {}'.format(user, fav_food[user]))
    except KeyError:
        print("{} hasn't taken the poll".format(user))

That would iterate over all users and if there is no fav food for a particular user, then it just print what you've said. 这将遍历所有用户,如果特定用户没有最喜欢的食物 ,那么它只会打印您所说的内容。

You can try this 你可以试试这个

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")

This will output as- 这将输出为-

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")

Works like a charm, but worth keeping in mind that if a user were to have an empty string as their favourite food it would instead say that they had not take the poll 就像魅力一样工作,但要记住,如果用户将空字符串作为自己喜欢的食物,它会说他们没有参加调查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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