Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python Dictionary vs Set: What's the Difference?

Python Dictionary vs Set - Complete Comparison

Learn the key differences between Python dictionaries and sets and when to use each.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Dictionaries vs Sets – What's the Big Difference?
  • Structure: Key-Value vs Values Only
  • Uniqueness: Dictionaries Allow Duplicates
  • Ordering: Both Preserve Order
  • Performance: Which Is Faster?
  • Memory Usage
  • Mutability: Both Can Change
  • Available Methods
  • When to Use Each
  • Quick Summary Table
  • Common Mistakes
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • 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

1

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

2

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

3

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?

4

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

5

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

6

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

7

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

8

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

9
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

10

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.

Loading Pyodide... 0%
Python Code Editor
========================================
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:

1. What is the main difference between a dictionary and a set?
2. Can a set contain duplicate values?
3. Which uses less memory: dictionary or set?
4. Which method do you use to add an element to a set?
5. When should you use a set instead of a dictionary?

Frequently Asked Questions

Which is faster: dictionary or set? ▼

Both are very fast for membership testing (O(1)). For key lookup, dictionaries are the only choice.

Can I convert a list to a set? ▼

Yes! Use set(my_list). This removes all duplicates. Use list(my_set) to convert back.

Do dictionaries preserve order? ▼

Yes, starting from Python 3.7, dictionaries preserve insertion order. In Python 3.6, it was an implementation detail.

Can I use a dictionary as a set key? ▼

No, dictionary keys must be hashable. Dictionaries are mutable and not hashable.

Which uses less memory: dictionary or set? ▼

Sets use less memory than dictionaries because they don't store keys. For large datasets, the difference can be significant.

What's a common interview question about dictionaries and sets? ▼

The most common is: "What's the difference between a dictionary and a set?" Answer: Dictionaries have key-value pairs; sets have values only. "Can you use a dictionary as a set key?" Answer: No.

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 →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
Previous: Tuple vs Dictionary Next: Collections Assignments →