Lesson 19 of 34

Dictionaries: Names to Values

10 min 30 XP

A dictionary works like a real dictionary: every key has a value. Write key: value pairs inside { }. You look values up by key instead of by index.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

Asking for a missing key gives an error. get() returns None, or a default you choose, instead.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

Use items() to loop over keys and values together.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

Dictionaries are perfect for counting: count[ch] = count.get(ch, 0) + 1. This comes up in interviews all the time!

Challenge

+30 XP

Read a word with input(). Count how many times each letter appears using a dictionary, then print the dictionary. Example: "hello" → {'h': 1, 'e': 1, 'l': 2, 'o': 1}

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.