Solve “Find Intersection”

Free. Runs in your browser, no install.

Python · Collections & Basics

Set vs dictionary

Easysetdicthashcollections

Interview question

What is the difference between a set and a dictionary in Python?

How to answer

The short answer

Both sets and dictionaries are built on hash tables, but they store different things.

Set (set)

  • Unordered collection of unique elements.
  • Only stores values (no key/value pairs).
  • Membership tests and deduplication are O(1) average.
  • Elements must be hashable.

Dictionary (dict)

  • Unordered (insertion-ordered since 3.7) mapping of keys → values.
  • Keys must be unique and hashable; values can be anything.
  • Lookup, insert, and delete by key are O(1) average.

Mental model

A set is "do I have this item?" A dict is "what value is associated with this key?"

Python
# Set: unique values
skills = {"sql", "python", "sql"}
print(skills)              # {'sql', 'python'}
print("python" in skills)  # True

# Dict: key → value
employee = {"name": "Asha", "role": "DE", "years": 3}
print(employee["role"])    # DE
employee["years"] = 4

# Set operations
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}

# Dict keys behave like a set of hashables
print(employee.keys())

Common pitfall: {} creates an empty dict, not an empty set. Use set() for an empty set.

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill