0%

Dictionaries and Other Collections · practice

Create and Read a Dictionary

A literal uses curly braces:

book = {
    "title": "Kindred",
    "creator": "Octavia E. Butler",
    "year": 1979,
}

Each entry has three parts:

"title": "Kindred"
#  key       value

A colon separates the key from its . Commas separate one entry from the next.

The trailing comma after the final entry is optional. Keeping it makes the dictionary easier to extend and lets every entry follow the same pattern.

Values can have different types

The example holds two and one integer. That is normal:

event = {
    "name": "Python meetup",
    "seats": 40,
    "online": False,
}

A dictionary brings related facts together. The values do not need to share a type.

For now, use strings as keys. Python permits some other as keys, but field names such as "title" and "year" make beginner records especially readable.

Read by key

Use square brackets with the exact key:

print(book["title"])
print(book["year"])

This prints:

Kindred
1979

Key spelling and capitalization matter. "title" and "Title" are different keys.

An empty dictionary

Empty curly braces create an empty dictionary:

record = {}
print(type(record))

You will meet sets near the end of the chapter. Sets also use curly braces when they contain values, but {} always means an empty dictionary.

Ask for a key that exists

Bracket lookup expects the key to be present:

book["publisher"]

If "publisher" is missing, Python raises a . In this lesson, use known keys. Lesson 4 gives you two deliberate ways to handle optional fields.

Which value is a dictionary with the keys "name" and "score"?

Task

Create a named book with exactly these entries:

Key
"title""Kindred"
"creator""Octavia E. Butler"
"year"1979

Then use three bracket lookups to print the values in this exact order:

Kindred
Octavia E. Butler
1979