Harplife
Harplife

Reputation: 77

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.
I'd prefer to do it the most "Python" way, if possible.

I'd appreciate the help!

Upvotes: 0

Views: 68

Answers (3)

LukeBils
LukeBils

Reputation: 1

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

Upvotes: 0

Somya Avasthi
Somya Avasthi

Reputation: 121

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

Upvotes: 0

vishes_shell
vishes_shell

Reputation: 23484

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.

Upvotes: 1

Related Questions