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

Python Crash Course, 3rd Edition2-041

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)
9 views1 page

Python Crash Course, 3rd Edition2-041

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

This approach pulls all the values from the dictionary without check-

ing for repeats. This might work fine with a small number of values, but in a
poll with a large number of respondents, it would result in a very repetitive
list. To see each language chosen without repetition, we can use a set. A set
is a collection in which each item must be unique:

favorite_languages = {
--snip--
}

print("The following languages have been mentioned:")


for language in set(favorite_languages.values()):
print(language.title())

When you wrap set() around a collection of values that contains dupli-
cate items, Python identifies the unique items in the collection and builds a
set from those items. Here we use set() to pull out the unique languages in
favorite_languages.values().
The result is a nonrepetitive list of languages that have been mentioned
by people taking the poll:

The following languages have been mentioned:


Python
C
Rust

As you continue learning about Python, you’ll often find a built-in feature
of the language that helps you do exactly what you want with your data.

NOTE You can build a set directly using braces and separating the elements with commas:
>>> languages = {'python', 'rust', 'python', 'c'}
>>> languages
{'rust', 'python', 'c'}

It’s easy to mistake sets for dictionaries because they’re both wrapped in braces.
When you see braces but no key-value pairs, you’re probably looking at a set. Unlike
lists and dictionaries, sets do not retain items in any specific order.

TRY IT YOURSELF

6-4. Glossary 2: Now that you know how to loop through a dictionary, clean
up the code from Exercise 6-3 (page 99) by replacing your series of print()
calls with a loop that runs through the dictionary’s keys and values. When
you’re sure that your loop works, add five more Python terms to your glossary.
When you run your program again, these new words and meanings should
automatically be included in the output.

104 Chapter 6

You might also like