✨ Chapter 5 Notes – Dictionaries & Sets


📘 Dictionary.py

marks = {
    "Prathamesh": 100,
    "Harry": 90,
    "Larry": 80
}

marks1 = {}  # This is an empty dictionary

print(marks, type(marks))         # Shows entire dictionary with type
print(marks["Harry"])             # Access value using a key
# print(marks[0])  ❌ Gives KeyError (dictionaries aren't accessed by index)

🧠 Key Concepts:


📘 Dictionary methods.py

marks = {
    "Prathamesh": 100,
    "Harry": 90,
    "Larry": 80
}

print(marks.items())      # All key-value pairs as tuples
print(marks.keys())       # Only keys
print(marks.values())     # Only values

marks.update({"Prathamesh": 99, "Lucy": 10})  # Add/update key-value pairs
print(marks)

print(marks.get("Tarry"))     # ✅ Returns None (safe)
print(marks["Harry2"])        # ❌ Gives KeyError if key doesn't exist

⚠️ Use .get() over direct key access to avoid crashing on missing keys.


📘 sets.py

# Set is a collection of **unique** elements
s = {1, 2, 3}
e = set()  # Correct way to create an empty set

# e = {} will create an empty dictionary, NOT a set

# Sets are:
# ✅ Unordered
# ✅ Unindexed
# ✅ Do NOT allow duplicates

Example:

s = {1, 1, 2, 3}
print(s)  # Output: {1, 2, 3} (removes duplicate 1)

📘 setmethods.py

s = {1, 2, 3, 4, 56, 5, 67, 62}

s.add(29323)        # Add new item
print(s)

s.pop()             # Remove a random item
print(s)

s.copy()            # Returns a copy of the set