PythonLesson 10 of 16
Dictionaries in Python
A dictionary stores key-value pairs, like a menu: a drink and its price. You find a value by its key, not by position.
Key points
- {"latte": 250}: the key is left of the colon, the value right
- d["latte"] reads a value, d["cocoa"] = 200 adds or changes one
- d.get(key, fallback) doesn't crash when the key is missing
- for k, v in d.items(): walks through every pair
- Keys are unique and keep the order you added them in
Example
menu = {"latte": 250, "tea": 150}print(menu["latte"])menu["cocoa"] = 200print(menu.get("juice", "not on the menu"))for drink, price in menu.items(): print(drink, price)print("tea" in menu, len(menu))cocoa went to the end of the dictionary. get returned the fallback text instead of an error, because juice isn't on the menu.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Update the stock: 3 apples were sold and 8 plums arrived (key "plums"). The loop below prints what's left.
Output
What your program prints appears here.