In Python, curly braces {} can represent two completely different data structures:
- A set
- A dictionary
The difference depends on a single character:
The colon
:
Understanding this distinction is fundamental if you want to truly master Python’s core data structures.
Without : → It’s a Set
If you use curly braces without a colon, Python creates a set.
numbers = [1, 2, 2, 3, 3, 3]
my_set = {n for n in numbers}
print(my_set)
Output:
{1, 2, 3}
Why?
A set:
- Stores unique values only
- Automatically removes duplicates
- Is unordered
- Does not use key-value pairs
In this example, repeated values (2, 3) are discarded because sets enforce uniqueness.
With : → It’s a Dictionary
If you include a colon inside {}, Python creates a dictionary.
numbers = [1, 2, 2, 3, 3, 3]
my_dict = {n: n**2 for n in numbers}
print(my_dict)
Output:
{1: 1, 2: 4, 3: 9}
How to Read This Line
{n: n**2 for n in numbers}
You can read it as:
"Create a dictionary where the key is
n,
the value isn**2,
for eachninnumbers."
Structure breakdown:
{ key : value }
- The first
n→ becomes the key -
n**2→ becomes the value -
for n in numbers→ iterates over the list
Why Are There Only 3 Key-Value Pairs?
The original list contains 6 elements:
[1, 2, 2, 3, 3, 3]
But the resulting dictionary has only 3 pairs.
Why?
Because dictionary keys must be unique.
When Python processes this:
- First
2→ creates{2: 4} - Second
2→ overwrites{2: 4} - Same happens with
3
Dictionaries do not allow duplicate keys. If a key appears again, its value is overwritten.
That’s why the final result contains only:
{1: 1, 2: 4, 3: 9}
Important Edge Case: Empty Braces
One subtle but important detail:
empty = {}
This creates a dictionary, not a set.
To create an empty set, you must use:
empty_set = set()
Quick Comparison
| Syntax | Creates | Purpose |
|---|---|---|
{x} |
Set | Store unique values |
{x: y} |
Dictionary | Map keys to values |
{} |
Dictionary | Empty dict |
set() |
Set | Empty set |
Final Rule
If there is a colon : inside {}, you're creating a dictionary.
If there is no colon, you're creating a set.
That single character completely changes the meaning of the structure.
Small syntactic details like this are what separate someone who uses Python from someone who truly understands Python.
Top comments (0)