[go: up one dir, main page]

0% found this document useful (0 votes)
7 views1 page

Python Crash Course, 3rd Edition2-038

Uploaded by

darkflux514
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views1 page

Python Crash Course, 3rd Edition2-038

Uploaded by

darkflux514
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Now, in just a few lines of code, we can display all of the information

from the poll:

Jen's favorite language is Python.


Sarah's favorite language is C.
Edward's favorite language is Rust.
Phil's favorite language is Python.

This type of looping would work just as well if our dictionary stored the
results from polling a thousand or even a million people.

Looping Through All the Keys in a Dictionary


The keys() method is useful when you don’t need to work with all of the val-
ues in a dictionary. Let’s loop through the favorite_languages dictionary and
print the names of everyone who took the poll:

favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'rust',
'phil': 'python',
}

for name in favorite_languages.keys():


print(name.title())

This for loop tells Python to pull all the keys from the dictionary favorite
_languages and assign them one at a time to the variable name. The output
shows the names of everyone who took the poll:

Jen
Sarah
Edward
Phil

Looping through the keys is actually the default behavior when looping
through a dictionary, so this code would have exactly the same output if you
wrote:

for name in favorite_languages:

rather than:

for name in favorite_languages.keys():

You can choose to use the keys() method explicitly if it makes your code
easier to read, or you can omit it if you wish.
You can access the value associated with any key you care about inside
the loop, by using the current key. Let’s print a message to a couple of
friends about the languages they chose. We’ll loop through the names in

Dictionaries 101

You might also like