What Is a Dictionary?
A Python dictionary stores data as key-value pairs. Instead of using a numbered index like a list, you access values using a descriptive key — like looking up a word in a real dictionary.
student = {
"name": "Alex",
"grade": 8,
"score": 95
}
print(student["name"]) # Alex
print(student["score"]) # 95
💡
Keys vs. Indexes
Lists use numbers: data[0]. Dictionaries use names: data["name"]. Dictionaries are better when each piece of data has a label.
Updating & Adding Data
You can change a value or add a new key at any time by assigning to it:
student["score"] = 100 # update existing key
student["school"] = "OKS" # add new key
print(student)
Looping with .items()
Use .items() to loop through every key-value pair in a dictionary:
for key, value in student.items():
print(key, ":", value)
A list of dictionaries acts like a data table — each dictionary is one row:
students = [
{"name": "Alex", "score": 95},
{"name": "Jordan", "score": 88},
{"name": "Taylor", "score": 92}
]
for s in students:
print(s["name"], "scored", s["score"])
🆕
Real-World Use
When you load a CSV file with Python, each row often becomes a dictionary where the column name is the key. That's why mastering dicts is essential for data science!