Dictionaries & Sets
While lists are indexed by numbers, Dictionaries are indexed by Keys. Sets are unordered collections of unique elements.
1. Dictionaries (dict)
Equivalent to Objects in JS or HashMaps in Java.
user = {
"name": "Pradeep",
"age": 25,
"email": "pradeep@example.com"
}
print(user["name"]) # Pradeep
user["age"] = 26 # Update
2. Sets (set)
Sets automatically remove duplicates and are great for membership testing.
colors = {"red", "green", "blue", "red"}
print(colors) # {"red", "green", "blue"}
# Checking membership (Fast!)
if "blue" in colors:
print("Found it!")
3. Set Operations
Python sets support mathematical operations like union and intersection.
group_a = {1, 2, 3}
group_b = {3, 4, 5}
print(group_a | group_b) # Union: {1, 2, 3, 4, 5}
print(group_a & group_b) # Intersection: {3}
Dictionary Tip: Use the .get() method to access a key. If the key doesn't exist, it returns None instead of crashing your program.