DEV Community

Cover image for Python {} Explained: When Is It a Set and When Is It a Dictionary?
Felipe Cezar
Felipe Cezar

Posted on

Python {} Explained: When Is It a Set and When Is It a Dictionary?

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{1, 2, 3}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{1: 1, 2: 4, 3: 9}
Enter fullscreen mode Exit fullscreen mode

How to Read This Line

{n: n**2 for n in numbers}
Enter fullscreen mode Exit fullscreen mode

You can read it as:

"Create a dictionary where the key is n,

the value is n**2,

for each n in numbers."

Structure breakdown:

{ key : value }
Enter fullscreen mode Exit fullscreen mode
  • 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]
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

Important Edge Case: Empty Braces

One subtle but important detail:

empty = {}
Enter fullscreen mode Exit fullscreen mode

This creates a dictionary, not a set.

To create an empty set, you must use:

empty_set = set()
Enter fullscreen mode Exit fullscreen mode

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)