MyMisPal
← Python lessons
Lesson 8 of 13

Dictionaries

A dictionary stores “key: value” pairs. Think of it as a database row: the keys are the column names.

PYTHON
emp = {"id": 7, "name": "Lina", "dept": "IT", "salary": 13500}
print(emp["name"], emp["salary"])
emp["salary"] = 14000
emp["city"] = "Jeddah"
print(emp)
PYTHON
emp = {"id": 7, "name": "Lina", "dept": "IT"}
for key, value in emp.items():
    print(key, "->", value)
print(emp.get("phone", "not set"))

A list of dictionaries is a whole table. This code does what GROUP BY does in SQL:

PYTHON
employees = [
    {"name": "Sara", "dept": "Sales", "salary": 9500},
    {"name": "Omar", "dept": "Sales", "salary": 9000},
    {"name": "Lina", "dept": "IT", "salary": 13500},
]
by_dept = {}
for e in employees:
    by_dept[e["dept"]] = by_dept.get(e["dept"], 0) + e["salary"]
for dept in sorted(by_dept):
    print(dept, by_dept[dept])
Watch outemp["phone"] raises KeyError if the key is missing, while emp.get("phone") quietly returns None.

Exercises

Exercise 1

You have stock = {"Laptop": 25, "Router": 60, "Chair": 30}. Add "Monitor" with 35, then print the Router quantity, then the number of products.

Exercise 2

You have orders as (city, amount). Total the sales per city in a dictionary, then print each city and total in alphabetical order, like: Dammam 500.

Spotted a mistake on this page, or have an idea to improve the site?