You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Dictionaries and sets are two more essential Python data structures. Dictionaries map keys to values; sets store unique values with no duplicates.
A dictionary stores key-value pairs, defined with curly braces:
person = {
"name": "Alice",
"age": 30,
"city": "London"
}
Keys must be immutable (strings, numbers, tuples). Values can be anything.
print(person["name"]) # Alice
print(person.get("age")) # 30
print(person.get("email", "N/A")) # N/A — default if key missing
Using get() is safer than bracket notation — it returns None (or a default) instead of raising a KeyError if the key does not exist.
person["age"] = 31 # update existing key
person["email"] = "alice@example.com" # add new key
del person["city"] # remove a key
removed = person.pop("age") # remove and return value
inventory = {"apples": 5, "bananas": 12, "cherries": 3}
for key in inventory:
print(key)
for value in inventory.values():
print(value)
for key, value in inventory.items():
print(f"{key}: {value}")
d = {"a": 1, "b": 2}
print(d.keys()) # dict_keys(['a', 'b'])
print(d.values()) # dict_values([1, 2])
print(d.items()) # dict_items([('a', 1), ('b', 2)])
print(len(d)) # 2
print("a" in d) # True — checks keys
squares = {x: x ** 2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
A set is an unordered collection of unique items:
colors = {"red", "green", "blue"}
numbers = {1, 2, 3, 2, 1} # duplicates removed automatically
print(numbers) # {1, 2, 3}
empty_set = set() # must use set(), not {} (that's an empty dict)
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union: {1, 2, 3, 4, 5, 6}
print(a & b) # intersection: {3, 4}
print(a - b) # difference: {1, 2}
print(a ^ b) # symmetric difference: {1, 2, 5, 6}
s = {1, 2, 3}
s.add(4)
s.remove(2) # raises KeyError if not present
s.discard(10) # no error if not present
print(s) # {1, 3, 4}
Sets are ideal for membership testing (much faster than lists for large collections) and for removing duplicates. Dictionaries are the go-to structure for storing structured data with named fields.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.