Dictionaries

A list finds things by position — item 0, item 1. A dictionary finds things by name. Instead of remembering that a student's GPA lives at index 2, you just ask for student["gpa"].

Creating a dictionary and looking things up

Curly braces hold a set of key: value pairs. You look up a value the same way you'd index a list, but with the key instead of a number:

>>> a student record
student = {"name": "Jordan", "grade": 9, "gpa": 3.7}
print(student["name"])
print(student["gpa"])
Output
Jordan
3.7

Adding and updating keys

Assign to a key that already exists and you overwrite its value; assign to a new key and it gets added:

>>> updating the record
student["grade"] = 10
student["school"] = "Lincoln High"
print(student)
Output
{'name': 'Jordan', 'grade': 10, 'gpa': 3.7, 'school': 'Lincoln High'}

Jordan moved up a grade, and a new "school" key was added on the end — dictionaries in modern Python remember the order keys were inserted in, which is why "school" shows up last rather than getting shuffled in alphabetically.

Looping over keys and values together

.items() gives you both the key and the value on each pass of a loop, which is usually what you actually want:

>>> a price list
prices = {"apple": 0.5, "banana": 0.25, "pear": 0.75}
for item, price in prices.items():
    print(item, "costs $" + str(price))
Output
apple costs $0.5
banana costs $0.25
pear costs $0.75

Checking for a key safely

Looking up a key that doesn't exist with square brackets crashes your program with a KeyError. .get() sidesteps that by letting you supply a fallback value:

>>> looking something up that might not be there
prices = {"apple": 0.5, "banana": 0.25}
print(prices.get("pear", 0))
print("apple" in prices)
Output
0
True
Note: every key in a dictionary has to be unique — assigning to a key that's already there replaces its value rather than creating a duplicate entry. Values, on the other hand, can repeat freely, and don't even need to all be the same type.