the dictionary as we did previously, but when the name matches one of our
friends, we’ll display a message about their favorite language:
favorite_languages = {
--snip--
}
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(f"Hi {name.title()}.")
1 if name in friends:
2 language = favorite_languages[name].title()
print(f"\t{name.title()}, I see you love {language}!")
First, we make a list of friends that we want to print a message to. Inside
the loop, we print each person’s name. Then we check whether the name
we’re working with is in the list friends 1. If it is, we determine the person’s
favorite language using the name of the dictionary and the current value of
name as the key 2. We then print a special greeting, including a reference to
their language of choice.
Everyone’s name is printed, but our friends receive a special message:
Hi Jen.
Hi Sarah.
Sarah, I see you love C!
Hi Edward.
Hi Phil.
Phil, I see you love Python!
You can also use the keys() method to find out if a particular person
was polled. This time, let’s find out if Erin took the poll:
favorite_languages = {
--snip--
}
if 'erin' not in favorite_languages.keys():
print("Erin, please take our poll!")
The keys() method isn’t just for looping: it actually returns a sequence of
all the keys, and the if statement simply checks if 'erin' is in this sequence.
Because she’s not, a message is printed inviting her to take the poll:
Erin, please take our poll!
Looping Through a Dictionary’s Keys in a Particular Order
Looping through a dictionary returns the items in the same order they
were inserted. Sometimes, though, you’ll want to loop through a dictionary
in a different order.
102 Chapter 6