Looping through dicitionary in Python

Viewed 40

I am learning from the book Python Crash Course by Eric Matthes and his solution for looping through the dictionary is not working as he claims.

Here is what I need to do:

#looping through dicitionary with names of people and their favorite programming language.
#if name matches one of my friends, we will display a message about their favorite language.
#it prints only Phil. Why???

favorite_languages = {'jen': 'python','sarah': 'c','edward': 'ruby','phil': 'python'}
friend = ['phil', 'jen', 'jakub']
for name in favorite_languages.keys():
    print(name)

if name in friend:
    print(" Hi " + name.title() +
    ", I see your favorite language is " +
    favorite_languages[name].title() + "!")
1 Answers

you missed the indent, and if the statement worked only with the last item of dict. You need to check every item in dict loop not only the last one. Solution:

favorite_languages = {'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python'}
    friend = ['phil', 'jen', 'jakub']
    for name in favorite_languages.keys():
        print(name)
        if name in friend:
            print(" Hi " + name.title() +
                  ", I see your favorite language is " +
                  favorite_languages[name].title() + "!")
Related