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 out
emp["phone"] raises KeyError if the key is missing, while emp.get("phone") quietly returns None.