Labs ICT
โญ Pro Login

Dictionaries

Python Dictionaries

A dictionary stores data in key-value pairs wrapped in curly braces {}. Keys must be unique and immutable. Values can be any type.

Creating a Dictionary

Define pairs with key: value separated by commas.

student = {
    "name": "Alice",
    "age": 22,
    "major": "Computer Science"
}
print(student)
Try it Yourself โ†’

Accessing Values

Use square brackets or get() to access values by key.

student = {"name": "Alice", "age": 22}
print(student["name"])
print(student.get("grade", "Not found"))
Try it Yourself โ†’

Dictionary Methods

Common methods: keys(), values(), items(), update(), pop().

car = {"brand": "Toyota", "model": "Corolla", "year": 2020}
print(car.keys())
print(car.values())
car.update({"year": 2022})
print(car)
Try it Yourself โ†’

Iterating Over a Dictionary

Loop through keys, values, or both.

scores = {"Math": 90, "Physics": 85, "Chemistry": 78}
for subject, score in scores.items():
    print(f"{subject}: {score}")
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which of these creates a dictionary?