- Structure — key-value pairs vs values only
- Uniqueness — dictionaries allow duplicate values, sets don't
- Performance — which one is faster for what
- Memory — which one uses less memory
- When to use — choosing the right one
Dictionaries vs Sets – What's the Big Difference?
Dictionaries and sets are both used to store collections of items, but they're built for very different purposes. They look similar (both use curly braces), but they work completely differently.
The short answer is: dictionaries store key-value pairs, sets store unique values only. But there's a lot more to it than that. Let's break it down.
💡 Here's the thing: The choice between a dictionary and a set affects how you access data, memory usage, and performance. Choose wisely!
Structure: Key-Value vs Values Only
Dictionaries Have Keys and Values, Sets Have Values Only
This is the most important difference. Dictionaries store key-value pairs. Sets store only values.
# Dictionary — key-value pairs
my_dict = {"name": "Alice", "age": 25, "city": "NYC"}
print(my_dict["name"]) # Alice — access by key
# Set — values only
my_set = {"Alice", "Bob", "Charlie"}
# print(my_set["Alice"]) # TypeError! No keys in sets
# Why this matters:
# Dictionaries are good for labeled data
# Sets are good for checking membership
What this means for you:
- Dictionaries — key-value pairs, access by key
- Sets — values only, access by membership
- Choose based on how you need to access data
Quick Check: How do you access a value in a dictionary? (Answer: Using a key)
Uniqueness: Dictionaries Allow Duplicates
Dictionaries Allow Duplicate Values, Sets Don't
Dictionaries can have duplicate values (but unique keys). Sets automatically remove duplicate values.
# Dictionary — duplicate values allowed
my_dict = {"a": 1, "b": 2, "c": 1} # Values can repeat
print(my_dict) # {'a': 1, 'b': 2, 'c': 1}
# Set — automatically removes duplicates
my_set = {1, 2, 2, 3, 3, 3, 4}
print(my_set) # {1, 2, 3, 4}
# Why this matters:
# Dictionaries can have duplicate values
# Sets only keep unique values
Key point:
- Dictionaries — allow duplicate values
- Sets — remove duplicate values automatically
- Sets are great for removing duplicates
Quick Check: What happens if you put duplicates in a set? (Answer: They are automatically removed)
Ordering: Both Preserve Order
Both Dictionaries and Sets Preserve Order (Python 3.7+)
In Python 3.7+, both dictionaries and sets preserve insertion order. This was a major change from earlier versions.
# Dictionary — preserves order
my_dict = {"first": 1, "second": 2, "third": 3}
print(my_dict) # {'first': 1, 'second': 2, 'third': 3}
# Set — preserves order (Python 3.7+)
my_set = {3, 1, 2}
print(my_set) # {3, 1, 2} — order is preserved!
# But sets are still not indexable!
# print(my_set[0]) # TypeError!
# Why this matters:
# You can rely on order for both, but sets are still not indexable
Key point:
- Dictionaries — preserve order, indexable by key
- Sets — preserve order, not indexable
- Both are ordered (Python 3.7+)
Quick Check: Do sets preserve order in Python 3.7+? (Answer: Yes)
Performance: Which Is Faster?
Both Are Fast for Membership Testing
Both dictionaries and sets use hash tables, which allow O(1) membership testing. They're both very fast.
import time
# Create data
big_dict = {i: i for i in range(1000000)}
big_set = set(range(1000000))
# Membership test in dictionary
start = time.time()
999999 in big_dict
dict_time = time.time() - start
# Membership test in set
start = time.time()
999999 in big_set
set_time = time.time() - start
print(f"Dict membership: {dict_time:.6f}s")
print(f"Set membership: {set_time:.6f}s")
# Both are very fast!
Performance summary:
- Dictionaries — fast for key lookups
- Sets — fast for membership testing
- Both use O(1) average time
Quick Check: Which is faster for checking if an item exists? (Answer: Both are fast)
Memory Usage
Sets Use Less Memory Than Dictionaries
Sets use less memory than dictionaries because they don't store keys. Dictionaries have overhead for storing key-value pairs.
import sys
# Create dictionary and set with same data
my_dict = {i: i for i in range(1000)}
my_set = set(range(1000))
print(f"Dict size: {sys.getsizeof(my_dict)} bytes")
print(f"Set size: {sys.getsizeof(my_set)} bytes")
# Output example:
# Dict size: 36,960 bytes
# Set size: 32,984 bytes
# Sets use less memory than dictionaries!
Memory summary:
- Sets — use less memory
- Dictionaries — use more memory (store keys + values)
- For large datasets, memory matters
Quick Check: Which uses less memory: dictionary or set? (Answer: Set)
Mutability: Both Can Change
Both Dictionaries and Sets Are Mutable
Both dictionaries and sets can be changed after creation. You can add, remove, or modify elements.
# Dictionary — mutable
my_dict = {"a": 1, "b": 2, "c": 3}
my_dict["a"] = 10 # Change
my_dict["d"] = 4 # Add
del my_dict["b"] # Remove
print(my_dict) # {'a': 10, 'c': 3, 'd': 4}
# Set — mutable
my_set = {1, 2, 3}
my_set.add(4) # Add
my_set.remove(2) # Remove
my_set.add(3) # No effect (already exists)
print(my_set) # {1, 3, 4}
# Both can change, but they change differently:
# Dictionaries change by key
# Sets change by value
Key point:
- Both dictionaries and sets are mutable
- Dictionaries maintain key-value structure
- Sets maintain uniqueness
Available Methods
What You Can Do With Each
Dictionaries and sets have different methods because they're used for different things.
# Dictionary methods
my_dict = {"a": 1, "b": 2, "c": 3}
print(my_dict.keys()) # dict_keys(['a', 'b', 'c'])
print(my_dict.values()) # dict_values([1, 2, 3])
print(my_dict.items()) # dict_items([('a', 1), ('b', 2), ('c', 3)])
my_dict.pop("b") # Remove
my_dict.update({"d": 4}) # Add
print(my_dict) # {'a': 1, 'c': 3, 'd': 4}
# Set methods
my_set = {1, 2, 3}
my_set.add(4) # Add
my_set.remove(2) # Remove
my_set.union({4, 5}) # Combine sets
my_set.intersection({3, 4}) # Find common
my_set.difference({4, 5}) # Elements in set but not in another
print(my_set) # {1, 3, 4}
Key difference:
- Dictionaries — keys(), values(), items(), pop(), update(), get()
- Sets — add, remove, union, intersection, difference
- Choose based on what you need to do
When to Use Each
Which One Should You Choose?
# Use dictionaries when:
# 1. You have labeled data
user = {"name": "Alice", "age": 25, "city": "NYC"}
# 2. You need to look up by a meaningful key
print(user["name"]) # Alice
# 3. You have key-value pairs
phone_book = {"Alice": "555-1234", "Bob": "555-5678"}
# 4. You need fast lookups by key
if "Alice" in phone_book:
print(phone_book["Alice"])
# Use sets when:
# 1. You need unique values
unique_visitors = {"alice", "bob", "charlie"}
# 2. You need fast membership testing
if "alice" in unique_visitors:
print("Alice visited!")
# 3. You need set operations
set1 = {"python", "java", "c++"}
set2 = {"python", "flask"}
common = set1.intersection(set2)
# 4. Order doesn't matter (though it is preserved)
tags = {"python", "tutorial", "beginner"}
Simple rule of thumb:
- Use dictionaries — when you have key-value data
- Use sets — when you need unique values or set operations
- When in doubt, ask: "Do I need a key or just a value?"
Quick Summary Table
| Feature | Dictionary | Set |
|---|---|---|
| Structure | Key-value pairs | Values only |
| Duplicate Values | Allowed ✅ | Not Allowed ❌ |
| Order | Preserved ✅ | Preserved (3.7+) ✅ |
| Access | By key | Membership only |
| Membership Speed | Fast (O(1)) ✅ | Fast (O(1)) ✅ |
| Memory | Larger | Smaller ✅ |
| Mutability | Mutable ✅ | Mutable ✅ |
| Methods | keys, values, items, pop, update ✅ | add, remove, union, intersection ✅ |
| Best For | Labeled data, lookups | Unique data, set operations |
Common Mistakes
Things to Watch Out For
Using a Dictionary When You Only Need Unique Values
# WRONG — dictionary is overkill
visitors = {"alice": True, "bob": True, "charlie": True}
# CORRECT — use a set
visitors = {"alice", "bob", "charlie"}
Using a Set When You Need Key-Value Pairs
# WRONG — set can't store key-value pairs
user = {"Alice", 25, "NYC"} # This is a set of values!
# CORRECT — use a dictionary
user = {"name": "Alice", "age": 25, "city": "NYC"}
Assuming Set Order in Older Python Versions
# WRONG — relying on set order in Python 3.6-
my_set = {1, 2, 3}
# Order was not guaranteed in older versions
# CORRECT — don't rely on set order
# Use a list if order matters
Quick Check: What's the most common mistake with dictionaries and sets? (Answer: Using a dictionary when a set would work, or vice versa)
Try It Yourself
Compare dictionaries and sets in the editor below. Change the code and see what happens.
DICTIONARY VS SET COMPARISON
========================================
Dictionary: {'a': 1, 'b': 2, 'c': 3}
Set: {1, 2, 3}
1. STRUCTURE
Dict['a']: 1 (by key)
Set[0] would give an error (no keys)
2. DUPLICATE VALUES
Dict with duplicates: {'a': 1, 'b': 2, 'c': 1}
Set with duplicates: {1, 2}
3. PERFORMANCE (MEMBERSHIP)
Dict membership: 0.000001s
Set membership: 0.000001s
4. MEMORY USAGE
Dict size: 184 bytes
Set size: 216 bytes
5. METHODS
Dict methods: keys(), values(), items(), pop(), update(), get()
Set methods: add(), remove(), union(), intersection(), difference()
Dictionary vs Set comparison complete!
You've Got It!
You now understand the key differences between dictionaries and sets — structure, uniqueness, ordering, performance, memory, and when to use each. This is a common interview question, so you're ready!
Quick Quiz
Test what you've learned:
Frequently Asked Questions
Which is faster: dictionary or set?
Can I convert a list to a set?
set(my_list). This removes all duplicates. Use list(my_set) to convert back.
Do dictionaries preserve order?
Can I use a dictionary as a set key?
Which uses less memory: dictionary or set?
What's a common interview question about dictionaries and sets?
Where to Go From Here
Now that you understand dictionaries and sets, check out these related topics:
List vs Dictionary
Compare lists with dictionaries for indexed vs key-value data.
Learn More →Tuple vs Set
Compare tuples with sets for ordered vs unique data.
Learn More →Collections Assignments
Practice what you've learned with assignments.
Learn More →