Dictionaries and Sets
Key-value storage with dict, and unique unordered collections with set.
2 min read
Lists and tuples are about order. Dictionaries and sets solve a different problem: fast lookup by key, and uniqueness, respectively.
Dictionaries
A dict maps keys to values:
user = {
"name": "Ada",
"age": 25,
"active": True,
}
print(user["name"]) # Ada
user["age"] = 26 # update an existing key
user["email"] = "a@x.com" # add a new keyLooking up a key that doesn't exist raises a KeyError. .get() avoids the crash and lets you supply a fallback:
print(user.get("phone")) # None -- key missing, no error
print(user.get("phone", "N/A")) # N/A -- custom defaultCheck for a key with in, and remove one with del or .pop():
if "email" in user:
print("Has an email on file")
del user["active"]
removed = user.pop("age") # removes 'age' and returns its valueIterating over a dictionary
for key in user:
print(key)
for key, value in user.items():
print(f"{key}: {value}")
for value in user.values():
print(value).items() is the most common form — it gives you both the key and value in one pass, instead of looking the value up separately inside the loop.
Dictionaries preserve insertion order
Since Python 3.7, dictionaries remember the order keys were added, and iterating reflects that order. This is a language guarantee, not an implementation detail you're relying on by accident.
Sets
A set holds unique, unordered values — duplicates are automatically dropped:
tags = {"python", "web", "python", "backend"}
print(tags) # {'python', 'web', 'backend'} -- duplicate collapsedSets are built for membership checks and mathematical set operations:
a = {1, 2, 3}
b = {2, 3, 4}
print(a & b) # {2, 3} -- intersection
print(a | b) # {1, 2, 3, 4} -- union
print(a - b) # {1} -- difference
print(3 in a) # TrueChecking in on a set is dramatically faster than checking in on a list for large collections, because a set is backed by the same hashing mechanism as a dictionary's keys rather than needing to scan item by item.
When to reach for each
Use a dict whenever data is naturally keyed — a user record, a config of settings, counts keyed by name. Use a set when you care about uniqueness or fast membership testing and don't care about order — deduplicating a list, or checking "have I seen this before" as you process items:
seen = set()
for item in ["a", "b", "a", "c"]:
if item not in seen:
seen.add(item)
print(item) # a, b, c -- each printed onceTest what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.