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:
student = {"name": "Jordan", "grade": 9, "gpa": 3.7}
print(student["name"])
print(student["gpa"])
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:
student["grade"] = 10 student["school"] = "Lincoln High" print(student)
{'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:
prices = {"apple": 0.5, "banana": 0.25, "pear": 0.75}
for item, price in prices.items():
print(item, "costs $" + str(price))
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:
prices = {"apple": 0.5, "banana": 0.25}
print(prices.get("pear", 0))
print("apple" in prices)
0 True