What Is a Dictionary?
You know lists, which store items in order by position. But what if you want to look up data by name instead of counting from zero? That is where dictionaries shine. A dictionary stores pairs of
key and value. The key acts like an address label; the value holds your actual data.Think of a real-world phone book. You do not ask for "the third entry." You say, "Alice's number?" In code, you write
phone_book['Alice'] and get her number back instantly.my_scores = {'math': 95, 'english': 88}
print(my_scores)Notice the curly braces
{}. Inside them, each pair uses a colon : to separate key from value. The keys here are strings, so they need quotes like any other string. Keys can be any type that does not change, such as strings and numbers.Reading and Updating Values
inventory = {'apples': 5, 'bananas': 3}
# Read a value
count = inventory['apples']
print(count)
# Update an existing key
inventory['apples'] = 10
# Add a new key-value pair
inventory['oranges'] = 7
print(inventory)When you assign to
dict[key], Python checks if that key exists. If yes, it replaces the old value. If no, it creates a brand-new entry. This makes adding items as easy as writing one line.Safe Lookups with .get()
students = {'Alice': 90, 'Bob': 85}
# Direct access: works only if key exists
print(students['Alice'])
# Safe lookup with default value
score = students.get('Charlie', 'No score yet')
print(score)
# Check membership first
if 'Dana' in students:
print(students['Dana'])The
.get(key, default) method returns default when the key is missing. This keeps your program running smoothly even with incomplete data.Looping Through a Dictionary
colors = {'red': 255, 'green': 128}
for name, value in colors.items():
print(f"{name} has value {value}")The
.items() method gives you both the key and value together. You unpack them into two variables inside your for loop. This pattern is how most real-world code walks through dictionary data.