Mingming Li — Click any blue heading below to expand the content.
A dictionary stores data in key-value pairs. Each key is unique and is used to access its corresponding value. Dictionaries are created using curly braces { }.
# Dictionary examples
student = {"name": "Alice", "age": 25, "grade": "A"}
person = {
"first_name": "John",
"last_name": "Doe",
"age": 30,
"city": "New York"
}
empty = {}
# Accessing values
print(student["name"]) # "Alice"
print(student["age"]) # 25
student = {"name": "Alice", "age": 25, "grade": "A"}
# Safe access with get() (no error if key missing!)
print(student.get("name")) # "Alice"
print(student.get("score")) # None (no error!)
print(student.get("score", 0)) # 0 (default value)
# Adding or updating
student["city"] = "Boston" # add new key
student["age"] = 26 # update existing key
# Removing items
del student["grade"] # remove specific key
age = student.pop("age") # remove and return value
last_item = student.popitem() # remove and return last item
# Other useful methods
student.clear() # remove all items
keys = student.keys() # get all keys
values = student.values() # get all values
items = student.items() # get all key-value pairs
len(student) # number of items
# Check if key exists
if "name" in student:
print("Name exists!")
.get() instead of [] when you're not sure if a key exists. It won't crash your program!
student = {"name": "Alice", "age": 25, "city": "Boston"}
# Loop through keys
for key in student:
print(key, student[key])
# Loop through values
for value in student.values():
print(value)
# Loop through key-value pairs (MOST USEFUL!)
for key, value in student.items():
print(f"{key}: {value}")
# Dictionary comprehension
squares = {x: x*x for x in range(1, 6)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
.items() gives you both key and value at the same time. It's the most common way to loop through dictionaries!
Dictionaries can contain other dictionaries. This is great for complex data like game characters, students, or settings.
# Nested dictionary example
students = {
"student1": {"name": "Alice", "age": 20, "grade": "A"},
"student2": {"name": "Bob", "age": 22, "grade": "B"},
"student3": {"name": "Charlie", "age": 21, "grade": "A"}
}
# Accessing nested values
print(students["student1"]["name"]) # "Alice"
print(students["student2"]["grade"]) # "B"
# Looping through nested dictionary
for student_id, info in students.items():
print(f"{student_id}: {info['name']} - {info['grade']}")
# Game character example
game = {
"player": {"name": "Hero", "health": 100, "position": (10, 20)},
"enemies": [{"name": "Goblin", "health": 30}, {"name": "Orc", "health": 50}],
"score": 0,
"active": True
}
| Feature | Dictionary | List |
|---|---|---|
| Indexing | Keys (any immutable type) | Integers (0, 1, 2...) |
| Access speed | Very fast (hash table) | Fast |
| When to use | Lookup by name/label, fast searches | Ordered sequences, simple lists |
| Memory | More memory | Less memory |
# When to use dictionary:
student_grades = {"Alice": 85, "Bob": 92, "Charlie": 78} # lookup by name
# When to use list:
scores = [85, 92, 78] # simple ordered collection
# Converting between list and dictionary
keys = ["a", "b", "c"]
values = [1, 2, 3]
dictionary = dict(zip(keys, values)) # {'a': 1, 'b': 2, 'c': 3}
# Counting letters (most common use case!)
word = "hello world"
char_count = {}
for char in word:
char_count[char] = char_count.get(char, 0) + 1
print(char_count) # {'h':1, 'e':1, 'l':3, 'o':2, ' ':1, 'w':1, 'r':1, 'd':1}
# Using defaultdict (even easier!)
from collections import defaultdict
counts = defaultdict(int) # default value is 0
counts["apple"] += 1 # works even if "apple" didn't exist!
# Merging dictionaries (Python 3.5+)
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = {**dict1, **dict2} # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Using update() method
dict1.update(dict2) # adds dict2's items to dict1
dict[key] = dict.get(key, 0) + 1 is a classic.
# CREATING
d = {} # empty dictionary
d = {"key": "value"} # with items
d = dict(name="Alice", age=25) # using dict() constructor
# ACCESSING
d["key"] # access (raises KeyError if missing)
d.get("key") # access (returns None if missing)
d.get("key", default) # with default value
# ADDING/UPDATING
d["new_key"] = "new_value" # add or update
d.update({"k1": 1, "k2": 2}) # merge another dictionary
# REMOVING
del d["key"] # remove key
value = d.pop("key") # remove and return value
d.popitem() # remove and return last item
d.clear() # remove all items
# CHECKING
"key" in d # check if key exists
len(d) # number of items
# ITERATING
for key in d: # loop through keys
for value in d.values(): # loop through values
for key, value in d.items(): # loop through pairs (BEST!)
# COMPREHENSION
squares = {x: x*x for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
Look at this code from our game. Can you spot the dictionary?
# In our game, we could store player stats in a dictionary
player = {
"name": "Runner",
"score": 0,
"high_score": 0,
"position": (80, 300),
"is_alive": True
}
# Access player's score
print(f"Score: {player['score']}")
# Update score
player['score'] += 10
player["name"] or player.get("name")player["level"] = 1if "health" in player: or player.get("health")Try these exercises to practice dictionaries. Write your code in Thonny.
student dictionary with keys "name", "age", "major". Print the name.person = {"name":"John", "age":30, "city":"NYC"}.dict1={"a":1,"b":2} and dict2={"c":3,"d":4}.inventory = {"apples":10, "bananas":5}.{"Alice":85, "Bob":92, "Charlie":78}.{"Alice":85, "Bob":92, "Charlie":78, "Diana":95}..get() instead of [] when unsure.dict[key] = value to add items.list(dict.keys()) instead.from collections import defaultdictprint(dict.keys()) to see all keys. Use if key in dict: before accessing.
dict[key] and dict.get(key)?d = {} or d = dict()dict[key]dict[key] raises KeyError if missing; .get() returns None (or a default).dict["new_key"] = valuefor key, value in dict.items():.get() to safely access values.items()