Lecture 4 : Sets and Dictionary in Python | DSA in Python

Learn Sets and Dictionary in Python to make your programs faster and more efficient. This article explains their syntax, common operations, and fast lookup capabilities. You will also learn how these data structures work as hash maps in Python and why they are important for learning Python DSA.
authorImageVarun Saharawat16 Jun, 2026
Lecture 4 : Sets and Dictionary in Python | DSA in Python

Many programmers face situations where their code becomes slow because it repeatedly searches through large lists to find values. When working with thousands or even millions of records, checking items one by one can take a lot of time and reduce performance. This article helps solve that problem by explaining Sets and Dictionary in Python collections and showing how these data structures improve data retrieval speed.

What Are Sets and Dictionary in Python?

Python provides several built-in data structures for storing and managing data. While lists and tuples store data in a sequence, sets and dictionaries use a different system that allows much faster searching and access to data.

A Python set is an unordered collection of unique elements in Python. Sets are changeable, meaning that after you create a set, you can add or remove objects. However, values inside a set have to be immutable, like numbers, strings or tuples.

A Python Dictionary is a mutable data structure that holds data in key-value pair form. The key must be unique and unchangeable . The value can be any data type : integers , strings , lists , other dictionaries , etc .

Sets and Dictionary in Python Example

# Quick declaration of sets and dictionaries

sample_set = {1, 2, 3, 4, 5}

sample_dict = {

    "name": "Joe",

    "age": 10,

    "city": "Paris"

}

In this example, the set stores a collection of unique numbers, while the dictionary stores information using keys and values.

In DSA in Python, sets and dictionaries are very important because they provide fast ways to store, search, and manage data. Instead of checking items one by one like a list, these structures use hashing to find values quickly. Because of their speed and flexibility, sets and dictionaries are widely used in algorithms, data processing tasks, and real-world software applications. Learning how they work helps you build faster and more efficient programs..

How do Sets and Dictionary in Python Optimise Lookups?

The primary advantage of using a set or a dictionary over a list lies in how elements are found inside system memory. A list requires sequential scanning from the very first element to the last, leading to time consumption that increases linearly with data size.

Sets and dictionaries in Python eliminate sequential searching entirely by implementing a technique called hashing. In simple terms, they act as hash maps in Python, where a mathematical hash function maps data elements directly to fixed memory slots.

Feature

Python List

Python Set

Python Dictionary

Ordering

Ordered sequence

Unordered collection

Ordered (Since Python 3.7+)

Duplicates

Fully allowed

Automatically dropped

Duplicate keys prohibited

Index Type

Numeric positional index

No indexing allowed

Custom key-based lookup

Search Mechanism

Linear sequential search

Hash-based direct access

Hash-based direct access

Lookup Speed

Slower for membership tests

Exceptionally fast ($O(1)$)

Exceptionally fast ($O(1)$)

Sets and Dictionary in Python Operations

Building a functional command over Sets and dictionaries in Python requires a deep understanding of their basic built-in methods, constructors, and item manipulation protocols.

Operations for Python Sets

You can initialize an empty set by invoking the explicit set() constructor. Using raw curly brackets without items ({}) creates a dictionary by default, so the constructor is mandatory for empty sets.

  • Adding items: Use the .add() method to pass an element into the set. Duplicates are filtered out automatically.

  • Removing items: Use the .remove() method to eliminate a specific element. If the value does not exist, it triggers an error.

  • Membership testing: Use the in operator to verify if an item exists within the set instantaneously.

Python

# Initializing and altering a set
my_set = {1, 2, 3, 4, 5, 6, 7}
my_set.add(8)        # Result: {1, 2, 3, 4, 5, 6, 7, 8}
my_set.remove(7)     # Result: {1, 2, 3, 4, 5, 6, 8}

# Testing membership
print(6 in my_set)   # Returns: True

Operations for Python Dictionaries

Dictionaries store elements as explicit key-value pairs separated by a colon, wrapped entirely in curly brackets.

  • Accessing values: Access entries by specifying the target key name inside standard square brackets [] or by calling the .get() method.

  • Modifying/Adding values: Assign a value to an existing key to update it, or declare a completely new index key to append a pair.

  • Removing values: Use the del keyword or call .pop() with the key name to clear specific entries. The .clear() method empties the dictionary entirely.

Python

# Operating a Python dictionary
my_dict = {"name": "Joe", "age": 10, "city": "Paris"}

# Accessing an item
print(my_dict["name"])  # Returns: 'Joe'

# Adding a new key-value pair
my_dict["new_key"] = "new_value"

# Deleting an entry
del my_dict["new_key"]

Mathematical Sets and Dictionary in Python

One of the main purposes of sets in Python DSA is comparing or combining different groups of data records. Python provides built-in methods to perform standard mathematical set operations effortlessly.

1. Union

The union operation combines all elements from both sets, discarding any duplicate entries that appear in both collections.

Python

set1 = {1, 3, 5, 6}
set2 = {1, 2, 3, 4}
print(set1.union(set2))  # Returns: {1, 2, 3, 4, 5, 6}

2. Intersection

The intersection operation targets and returns only the common elements present simultaneously in both datasets. This is highly useful for identifying mutual attributes, friends, or values.

Python

print(set1.intersection(set2))  # Returns: {1, 3}

3. Difference

The difference operation isolates elements that reside in the primary set but are completely absent from the comparison set.

Python

print(set1.difference(set2))  # Returns: {5, 6}

4. Subset Validation

You can check if an entire dataset is completely enclosed within another collection by running a boolean validation test.

False

Jun 11, 12:30 AM

Open

Try again without Canvas

FAQs

Can a set contain duplicate elements in Python?

No, a set cannot contain duplicate elements. A set is designed to store only unique values. If you try to add a value that already exists in the set, Python ignores it and does not add it again.

What types of objects can be used as dictionary keys in Python?

Dictionary keys must be immutable objects. Common examples include integers, floats, strings, and tuples that contain only immutable values. Mutable objects such as lists, sets, and dictionaries cannot be used as keys because they are not hashable.

Why are sets and dictionaries faster than lists?

Lists usually need to check items one by one when searching for a value, which takes O(n) time. Sets and dictionaries use hashing, which allows them to find values much faster, often in O(1) time. This makes them a better choice for handling large amounts of data.

Does a Python dictionary keep items in order?

Yes. In Python 3.7 and beyond, dictionaries keep the order in which items are inserted. That means the keys and values remember the order they were placed into the dictionary.

What is the difference between a set and a frozenset?

A set is mutable, which means you can add, remove, or update items after creating it. A frozenset is immutable, meaning its contents cannot be changed once it is created. Because of this, a frozenset can be used as a dictionary key or stored inside another set.
Popup Close ImagePopup Open Image
Talk to a counsellorHave doubts? Our support team will be happy to assist you!
Popup Image
avatar

Get Free Counselling Today

and Clear up all your Doubts

Talk to Our Counsellor just by filling out the form.
Student Name
Phone Number
IN
+91
OTP
Email Id
Join 15 Million students on the app today!
Point IconLive & recorded classes available at ease
Point IconDashboard for progress tracking
Point IconLakhs of practice questions
Download ButtonDownload Button
Banner Image
Banner Image