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!