Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. Set vs dictionary

Python · Collections & Basics

Set vs dictionary

Easypython-02
setdicthashcollections

Question

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

Solution

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?"

# 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.

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext