Collections Lesson 17 of 23
Python Dictionaries
Store labeled data in dictionaries with keys and values — read with [] and get(), add, change and delete entries, loop with items(), and build a price list and vote counter.
A list is great when items are in order. But often you want to look things up by a label: the price of "kape", the phone number of "Ana", the grade in "Math". For that, Python has the dictionary (dict): a collection of key–value pairs.
Creating a dictionary
student = {
"name": "Maria Clara",
"grade": 10,
"section": "Rizal",
"average": 94.5,
}
print(student)
Output
{'name': 'Maria Clara', 'grade': 10, 'section': 'Rizal', 'average': 94.5}Each entry has a key (before the colon) and a value (after). Keys are usually strings and must be unique.
Reading values
print(student["name"])
print(student.get("section"))
print(student.get("email")) # missing key → None
print(student.get("email", "no email")) # with a default
Output
Maria Clara Rizal None no email
print(student["email"])
Error
KeyError: 'email'
Adding, changing and deleting
prices = {"pandesal": 25, "kape": 8}
prices["itlog"] = 9 # add
prices["kape"] = 10 # change
del prices["pandesal"] # delete
print(prices)
print(len(prices))
print("kape" in prices) # checks keys
Output
{'kape': 10, 'itlog': 9}
2
TrueLooping through a dictionary
prices = {"Pandesal": 25, "Kape": 8, "Itlog": 9, "Noodles": 15}
for item in prices: # keys
print(item, end=" ")
print()
for item, price in prices.items(): # keys and values
print(f"{item:<10} ₱{price:>5.2f}")
print("Total of one each:", sum(prices.values()))
Output
Pandesal Kape Itlog Noodles Pandesal ₱25.00 Kape ₱ 8.00 Itlog ₱ 9.00 Noodles ₱15.00 Total of one each: 57
d.keys(): all keysd.values(): all valuesd.items(): all (key, value) pairs
Counting with a dictionary
A classic use: counting how many times each thing appears.
votes = ["Ana", "Ben", "Ana", "Carla", "Ben", "Ana", "Carla", "Ana"]
tally = {}
for name in votes:
tally[name] = tally.get(name, 0) + 1
print(tally)
winner = max(tally, key=tally.get)
print("Winner:", winner, "with", tally[winner], "votes")
Output
{'Ana': 4, 'Ben': 2, 'Carla': 2}
Winner: Ana with 4 votestally.get(name, 0) + 1 means "the current count, or 0 if this is the first vote, plus one".
A shopping program
prices = {"pandesal": 25, "kape": 8, "itlog": 9}
total = 0
while True:
item = input("Item (or 'done'): ").strip().lower()
if item == "done":
break
if item not in prices:
print("Wala kaming", item)
continue
qty = int(input("How many? "))
total += prices[item] * qty
print(f"Total: ₱{total}")
Output
Item (or 'done'): kape How many? 3 Item (or 'done'): softdrinks Wala kaming softdrinks Item (or 'done'): itlog How many? 6 Item (or 'done'): done Total: ₱78
Nested dictionaries and lists
Real data mixes lists and dictionaries. A list of dictionaries is like a table, where each dictionary is one row:
students = [
{"name": "Ana", "grades": {"Math": 88, "Science": 91}},
{"name": "Ben", "grades": {"Math": 76, "Science": 82}},
]
for s in students:
avg = sum(s["grades"].values()) / len(s["grades"])
print(f"{s['name']}: {avg:.1f}")
Output
Ana: 89.5 Ben: 79.0
This is exactly the shape of JSON data from websites, so these skills transfer directly to working with APIs.
Dictionary comprehension
prices = {"pandesal": 25, "kape": 8, "itlog": 9}
with_vat = {item: round(p * 1.12, 2) for item, p in prices.items()}
print(with_vat)
Output
{'pandesal': 28.0, 'kape': 8.96, 'itlog': 10.08}Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04