Python Dictionaries and Sets: When to Use Each
Introduction
Dictionaries and sets are two of Python's most useful built-in data structures. A dictionary maps keys to values for fast lookups, while a set stores unique items and supports mathematical set operations. This guide shows how each one works and how to choose between them.
Prerequisites
- Python 3.8 or newer installed
- Familiarity with lists and for-loops
Step-by-Step Guide
Step 1: Create a dictionary and read values
A dictionary stores key-value pairs inside curly braces. Use square brackets to read a value, or get() to supply a fallback when a key might be missing.
user = {"name": "Ava", "age": 30}
print(user["name"]) # Ava
print(user.get("email", "not set")) # not setStep 2: Add, update, and remove entries
Assign to a key to add or change it, and use del or pop() to remove it.
user["age"] = 31 # update
user["email"] = "ava@example.com" # add
del user["age"] # remove
print(user)Step 3: Loop over a dictionary
Use items() to get each key and value together.
for key, value in user.items():
print(key, "->", value)Step 4: Create a set of unique values
A set automatically discards duplicates. Sets are unordered, so don't rely on the print order.
tags = {"python", "code", "python"}
print(tags) # {'python', 'code'} (order may vary)
print("code" in tags) # TrueStep 5: Combine sets with set operations
Sets support union, intersection, and difference, which are handy for comparing collections.
a = {1, 2, 3}
b = {3, 4}
print(a | b) # union: {1, 2, 3, 4}
print(a & b) # intersection: {3}
print(a - b) # difference: {1, 2}FAQs
- When should I use a dictionary instead of a list?
- Use a dictionary when you look items up by a meaningful key (like a user ID or name). Use a list when order and position matter and you mostly loop through everything.
- Can any value be a dictionary key?
- Keys must be hashable, meaning immutable types such as strings, numbers, and tuples. Lists and other dictionaries can't be keys.
Summary
Reach for a dictionary when you need fast lookups by key, and a set when you need unique values or want to compare groups of items. Both offer near-constant-time membership checks on average.
Comments
Log in or create a free account to join the discussion.