Python Lesson 13: Dictionaries

🐍 Python CourseLesson 13 of 26 · 50% complete

A dictionary stores data as key-value pairs. Instead of positions, you access values by meaningful names. Think of a real dictionary: look up a word (key) to find its meaning (value).

Creating Dictionaries

person = {
    "name": "Alice",
    "age": 30,
    "city": "London",
    "is_student": False
}

scores = {"Alice": 95, "Bob": 87, "Charlie": 92}
empty = {}

Accessing Values

person = {"name": "Alice", "age": 30, "city": "London"}

print(person["name"])              # Alice
print(person["age"])               # 30

# .get() is safer — no crash if key missing
print(person.get("email"))         # None
print(person.get("email", "N/A"))  # N/A (default)

Modifying Dictionaries

person = {"name": "Alice", "age": 30}

person["email"] = "alice@example.com"  # add key
person["age"] = 31                     # update key
del person["age"]                      # remove key
removed = person.pop("email")          # remove and return

print(person)  # {"name": "Alice"}

Looping Over Dictionaries

grades = {"Alice": 95, "Bob": 87, "Charlie": 92}

# Loop over key-value pairs (most useful)
for name, grade in grades.items():
    print(f"{name}: {grade}")

# Keys only
for name in grades:
    print(name)

# Values only
for grade in grades.values():
    print(grade)

Nested Dictionaries

users = {
    "alice": {"age": 30, "score": 1500},
    "bob":   {"age": 25, "score": 2300}
}

print(users["alice"]["score"])   # 1500
users["alice"]["score"] += 100  # update nested

🏋️ Practice Task

Build a phonebook. Dictionary with 4 contacts (name -> phone). Ask user to search by name and print the number. Add a new contact. Print all contacts alphabetically.

💡 Hint: Use person.get(name, “Not found”). Use sorted(phonebook.keys()) for alphabetical order.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *