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!

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

Python 3.x For loop- Looping over a dictionary, Looping over a dictionary using all the keys or a list containing some of the keys. Display keys Duration: 3:23 Posted: Oct 5, 2016 How to Iterate Through a Dictionary in Python: The Basics. Dictionaries are an useful and widely used data structure in Python. As a Python coder, you’ll often be in situations where you’ll need to iterate through a dictionary in Python, while you perform some actions on its key-value pairs.

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.

Iterate over a dictionary in Python, Python3 code to iterate through all keys in a dictionary. statesAndCapitals = { List Of given states: Rajasthan Bihar Maharashtra Gujarat. In order to maintain the order of keys and values in a dictionary, use OrderedDict. filter_none. edit close. Python | Iterate through value lists dictionary While working with dictionary, we can have a case in which we need to iterate through the lists, which are in the keys of dictionaries. This kind of problem can occur in web development domain.

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

Iterating over dictionaries using 'for' loops, will simply loop over the keys in the dictionary, rather than the keys and values. In Python 3.x, iteritems() was replaced with simply items() , which returns a work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs,  In this tutorial, learn how to loop through dictionary elements in Python. To loop or iterate over each element of a dictionary variable, you have to use the for loop of Python. You can get the dictionary variable keys and values in the output. Use the for loop of the Python and use only keys or values in your programming.

Python Loop Through a Dictionary, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java  Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). To check whether a single key is in the dictionary, use the in keyword. Here is a small example using a dictionary:

Not using items() to iterate over a dictionary, Difference Python 2 and Python 3¶. In python 2.x the above examples using items would return a list with tuples containing the copied key-value pairs of  1.2 To loop every key and value from a dictionary – for k, v in dict.items(): for k, v in dict.items(): print(k,v) P.S items() works in both Python 2 and 3.

Python 3 Notes: More on for Loops, The .items() method on a dictionary induces a pseudo-list of (key, value) tuples. The for loop then can iterate over this list, and the bound variable should also be​  There are two ways of iterating through a Python dictionary object. One is to fetch associated value for each key in keys() list. >>> D1 = {1:'a', 2:'b', 3:'c'} >>> for k in D1.keys(): print (k, D1[k]) 1 a 2 b 3 c

Comments
  • Can you show some code?
  • Thanks, I tried it this way and it worked. It's what I had in mind logically. Definitely readable this way too!
  • You don't need to do in fav_food.keys(), you can simply do in fav_food.
  • an if statement would do. There is no need for try-except here.
  • Consider me old-school ☺. Anyway +1
  • @vishes_shell wow, thanks for the answer. I tried it the way you suggested and it worked. I guess, as a beginner, I wanted to tackle this with 'if' statement, but this way does feel a lot like the python way. Thank you.