Module 2: Lists, dictionaries and files · 10 min
Dictionaries
A dictionary stores pairs of key and value. Use it when each piece of data has a name.
student = {"name": "Bilal", "age": 20, "city": "Faisalabad"}
print(student["name"]) # Bilal
student["age"] = 21
student["email"] = "[email protected]"
print(student.get("phone", "none")) # none (no error if missing)
for key, value in student.items():
print(key, "->", value)
A list of dictionaries is the most common shape for small data sets, and it is the same shape as rows in a table or JSON from a web service.
students = [
{"name": "Ayesha", "marks": 88},
{"name": "Bilal", "marks": 71},
]
top = max(students, key=lambda s: s["marks"])
print(top["name"]) # Ayesha