Introduction
Python provides several built-in data structures that help developers store, organize, access and manage information efficiently.
When developing real-world applications, we frequently work with different types of information, such as student records, employee details, product information, customer data and registration records.
Python provides multiple data structures for managing this information, including:
- Lists
- Tuples
- Sets
- Dictionaries
In this tutorial, we will focus on two important Python data structures: Sets and Dictionaries.
A Set is used to store unique values, whereas a Dictionary stores information in key-value pairs.
For example, imagine that you are developing a student registration system for a training institute.
You want to:
- Store unique student registration IDs.
- Maintain student information.
- Access student details using their names or IDs.
- Update student information.
- Remove unnecessary records.
- Identify students enrolled in multiple courses.
Python Sets and Dictionaries make these operations easier.
By the end of this tutorial, you will understand how to create, access, update and manage Sets and Dictionaries using practical Python programs.
1. Understanding Python Sets
What is a Set in Python?
A Set is a built-in Python data structure used to store multiple unique elements in a single variable.
The most important characteristic of a Set is that it automatically removes duplicate values.
For example:
numbers = {10, 20, 30, 40}
print(numbers)
Output:
{10, 20, 30, 40}
Here, we created a Set containing four integer values.
Now consider another example:
numbers = {10, 20, 20, 30, 30, 40}
print(numbers)
Output:
{10, 20, 30, 40}
Notice that duplicate values have been removed automatically.
Even though we provided six values, Python retained only four unique values.
This makes Sets useful when working with information that should not contain duplicates.
Important Characteristics of Sets
- Sets do not contain duplicate elements.
- Sets are unordered collections.
- Sets are mutable, meaning we can add and remove elements.
- Sets do not support indexing or slicing.
- Set elements must be hashable.
- Sets can contain different hashable data types.
Example:
data = {10, "Python", 25.5, True}
print(data)
The order of elements in the output is not guaranteed.
Important: Never depend on the displayed order of Set elements. Python Sets are unordered collections.
2. Creating Sets in Python
There are two common ways to create a Set.
Method 1: Using Curly Braces
numbers = {10, 20, 30, 40}
print(numbers)
print(type(numbers))
Output:
{10, 20, 30, 40}
<class 'set'>
Method 2: Using the set() Constructor
We can also create a Set using the built-in set() function.
numbers = set([10, 20, 30, 40]) print(numbers)
Output:
{10, 20, 30, 40}
The set() constructor can also remove duplicates from an existing collection.
numbers = set([10, 20, 20, 30, 40, 40]) print(numbers)
Output:
{10, 20, 30, 40}
Creating an Empty Set
One important concept beginners should understand is how to create an empty Set.
Consider:
my_set = set() print(my_set) print(type(my_set))
Output:
set() <class 'set'>
We use set() to create an empty Set.
Important Difference Between {} and set()
Consider the following code:
a = {}
b = set()
print(type(a))
print(type(b))
Output:
<class 'dict'> <class 'set'>
Why does this happen?
In Python, empty curly braces {} represent an empty Dictionary.
To create an empty Set, we must use set().
Remember:
- {} creates an empty Dictionary.
- set() creates an empty Set.
3. Adding Elements to Sets
Python provides built-in methods to add individual or multiple elements to a Set.
3.1 The add() Method
The add() method inserts a single element into an existing Set.
Syntax:
set_name.add(element)
Example:
fruits = {"Apple", "Banana"}
fruits.add("Mango")
print(fruits)
Output:
{'Apple', 'Banana', 'Mango'}
Here, Mango is added to the existing Set.
What happens if we add an element that already exists?
fruits = {"Apple", "Banana"}
fruits.add("Apple")
print(fruits)
Output:
{'Apple', 'Banana'}
Python does not create another copy of Apple because Sets contain only unique elements.
3.2 The update() Method
The update() method adds multiple elements to an existing Set.
Syntax:
set_name.update(iterable)
Example:
fruits = {"Apple", "Banana"}
fruits.update(["Mango", "Orange", "Grapes"])
print(fruits)
Output:
{'Apple', 'Banana', 'Mango', 'Orange', 'Grapes'}
We can also use another Set:
numbers = {10, 20, 30}
numbers.update({40, 50, 60})
print(numbers)
Output:
{10, 20, 30, 40, 50, 60}
Difference between add() and update():
- add() inserts one element.
- update() inserts multiple elements from an iterable.
4. Removing Elements from Sets
Python provides different methods to remove elements from Sets.
4.1 The remove() Method
The remove() method removes a specified element.
Example:
numbers = {10, 20, 30, 40}
numbers.remove(20)
print(numbers)
Output:
{10, 30, 40}
Important: If the specified element does not exist, remove() raises a KeyError.
Example:
numbers = {10, 20, 30}
numbers.remove(100)
This produces a KeyError because 100 does not exist in the Set.
4.2 The discard() Method
The discard() method also removes an element.
However, there is an important difference.
If the specified element does not exist, discard() does not raise an error.
Example:
numbers = {10, 20, 30, 40}
numbers.discard(20)
numbers.discard(100)
print(numbers)
Output:
{10, 30, 40}
The program executes successfully even though 100 does not exist.
4.3 The pop() Method
The pop() method removes and returns an arbitrary element from a Set.
Example:
numbers = {10, 20, 30, 40}
removed = numbers.pop()
print("Removed:", removed)
print("Remaining:", numbers)
The removed element is not predictable because Sets are unordered.
4.4 The clear() Method
The clear() method removes all elements from a Set.
Example:
numbers = {10, 20, 30, 40}
numbers.clear()
print(numbers)
Output:
set()
5. Set Operations in Python
Set operations are particularly useful when comparing two collections of data.
Imagine a training institute offers two courses:
- Python Programming
- Django Development
Some students are enrolled in both courses.
We want to identify:
- All students enrolled in either course.
- Students enrolled in both courses.
- Students enrolled only in Python.
- Students enrolled in exactly one of the courses.
Python provides four important Set operations to perform these tasks.
Create Two Sets
python_students = {"Rahul", "Aman", "Priya"}
django_students = {"Aman", "Priya", "Rohit"}
5.1 Union Operation (|)
Union combines all unique elements from two Sets.
Example:
result = python_students | django_students print(result)
Output:
{'Rahul', 'Aman', 'Priya', 'Rohit'}
Union does not repeat common elements.
We can also use the union() method:
result = python_students.union(django_students) print(result)
Real-world application:
A training institute can use Union to generate a combined list of students enrolled in different courses without duplicating student names.
5.2 Intersection Operation (&)
Intersection returns only the common elements between two Sets.
Example:
result = python_students & django_students print(result)
Output:
{'Aman', 'Priya'}
These two students are enrolled in both courses.
We can also use:
result = python_students.intersection(django_students) print(result)
Real-world application:
Identify students who have enrolled in both Python and Django training programs.
5.3 Difference Operation (-)
Difference returns elements that exist in the first Set but not in the second Set.
Example:
result = python_students - django_students print(result)
Output:
{'Rahul'}
Rahul is enrolled in Python but is not included in the Django Set.
We can also use:
result = python_students.difference(django_students) print(result)
Remember that the order of the Sets matters in Difference.
For example:
print(django_students - python_students)
Output:
{'Rohit'}
5.4 Symmetric Difference (^)
Symmetric Difference returns elements that exist in either Set, but not in both.
Example:
result = python_students ^ django_students print(result)
Output:
{'Rahul', 'Rohit'}
Aman and Priya are excluded because they appear in both Sets.
We can also use:
result = python_students.symmetric_difference(django_students) print(result)
Summary of Set Operations
| Operation | Symbol | Purpose | |
| Union | ` | ` | Combines unique elements |
| Intersection | & | Finds common elements | |
| Difference | - | Finds elements in the first Set only | |
| Symmetric Difference | ^ | Finds elements not common to both |
6. Understanding Python Dictionaries
What is a Dictionary?
A Dictionary is a built-in Python data structure that stores information in key-value pairs.
Think about a student registration form.
A student has different details:
- Name
- Age
- Course
- City
Each piece of information has a label and a corresponding value.
For example:
| Key | Value |
| name | Rahul |
| age | 22 |
| course | Python |
| city | Ranchi |
Here:
- name is a key.
- Rahul is its value.
- age is a key.
- 22 is its value.
A Dictionary helps us organize related information in a structured way.
Creating a Dictionary
Example:
student = {
"name": "Rahul",
"age": 22,
"course": "Python",
"city": "Ranchi"
}
print(student)
Output:
{
'name': 'Rahul',
'age': 22,
'course': 'Python',
'city': 'Ranchi'
}
Important Characteristics of Dictionaries
- Dictionaries store information in key-value pairs.
- Dictionary keys must be unique.
- Values can be duplicated.
- Dictionaries are mutable.
- Dictionaries preserve insertion order.
- Values can be accessed using their keys.
- Dictionary keys must be hashable.
- Dictionary values can contain different data types.
Another Example: Employee Information
employee = {
"id": 101,
"name": "Amit",
"salary": 25000,
"department": "IT"
}
print(employee)
Here:
- id is a key.
- 101 is its value.
- name is a key.
- Amit is its value.
- salary is a key.
- 25000 is its value.
- department is a key.
- IT is its value.
7. Accessing Dictionary Values
One of the biggest advantages of Dictionaries is that we can access information directly using keys.
Consider:
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
7.1 Using Square Brackets []
We can access a Dictionary value by providing its key inside square brackets.
Example:
print(student["name"]) print(student["age"]) print(student["course"])
Output:
Rahul 22 Python
This method directly retrieves the value associated with the specified key.
However, if the key does not exist, Python raises a KeyError.
Example:
print(student["city"])
Since city does not exist in the Dictionary, Python raises an error.
7.2 Using the get() Method
The get() method provides another way to retrieve Dictionary values.
Example:
print(student.get("name"))
print(student.get("course"))
Output:
Rahul Python
What happens if the key does not exist?
print(student.get("city"))
Output:
None
Unlike square bracket access, get() returns None by default when the requested key is missing.
Providing a Default Value with get()
We can also provide a default value.
Example:
print(student.get("city", "Not Available"))
Output:
Not Available
This is useful when working with incomplete information.
Difference between [] and get():
| Method | Missing Key |
| student["city"] | Raises KeyError |
| student.get("city") | Returns None |
| student.get("city", "Unknown") | Returns Unknown |
8. Adding New Key-Value Pairs
Python allows us to add new information to an existing Dictionary.
Example:
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
student["city"] = "Ranchi"
print(student)
Output:
{
'name': 'Rahul',
'age': 22,
'course': 'Python',
'city': 'Ranchi'
}
Here, we added a new key called city with the value Ranchi.
We can also add an email address:
student["email"] = "[email protected]" print(student)
Now the Dictionary contains an additional key-value pair.
9. Updating Existing Dictionary Values
If we assign a new value to an existing key, Python updates its value.
Example:
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
student["age"] = 23
print(student)
Output:
{
'name': 'Rahul',
'age': 23,
'course': 'Python'
}
The age has changed from 22 to 23.
We can also update the course:
student["course"] = "Django" print(student)
Output:
{
'name': 'Rahul',
'age': 23,
'course': 'Django'
}
Remember: If a key already exists, assignment updates its value. If it does not exist, assignment creates a new key-value pair.
10. Removing Dictionary Elements
Python provides different methods to remove information from Dictionaries.
10.1 The pop() Method
The pop() method removes a specified key and returns its associated value.
Example:
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
removed_value = student.pop("course")
print("Removed:", removed_value)
print(student)
Output:
Removed: Python
{'name': 'Rahul', 'age': 22}
If the specified key does not exist and no default value is supplied, pop() raises a KeyError.
We can provide a default value:
print(student.pop("city", "Not Found"))
Output:
Not Found
10.2 The clear() Method
The clear() method removes all key-value pairs from a Dictionary.
Example:
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
student.clear()
print(student)
Output:
{}
The Dictionary still exists, but all its entries have been removed.
10.3 The del Keyword
We can also use the del keyword to remove a particular key.
Example:
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
del student["age"]
print(student)
Output:
{'name': 'Rahul', 'course': 'Python'}
11. Important Dictionary Methods
Python provides several built-in Dictionary methods that help us retrieve, update, copy and manage information.
11.1 keys() – Get All Keys
The keys() method returns a view containing all Dictionary keys.
Example:
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
print(student.keys())
Output:
dict_keys(['name', 'age', 'course'])
11.2 values() – Get All Values
The values() method returns a view containing all Dictionary values.
Example:
print(student.values())
Output:
dict_values(['Rahul', 22, 'Python'])
11.3 items() – Get Keys and Values Together
The items() method returns a view containing key-value pairs as tuples.
Example:
print(student.items())
Output:
dict_items([
('name', 'Rahul'),
('age', 22),
('course', 'Python')
])
This method is particularly useful when we want to work with both keys and values together.
11.4 get() – Retrieve Values
Example:
print(student.get("name"))
Output:
Rahul
11.5 update() – Add or Update Multiple Values
The update() method allows us to add or update multiple key-value pairs.
Example:
student.update({
"city": "Ranchi",
"age": 23
})
print(student)
Output:
{
'name': 'Rahul',
'age': 23,
'course': 'Python',
'city': 'Ranchi'
}
Here, age was updated and city was added.
11.6 pop() – Remove a Specified Key
student.pop("course")
print(student)
This removes the course key and its associated value.
11.7 clear() – Remove All Entries
student.clear() print(student)
Output:
{}
11.8 copy() – Create a Shallow Copy
The copy() method creates a shallow copy of a Dictionary.
Example:
student = {
"name": "Rahul",
"age": 22
}
new_student = student.copy()
print(new_student)
Output:
{'name': 'Rahul', 'age': 22}
A shallow copy creates a new outer Dictionary, but nested mutable objects are still shared.
Dictionary Methods Summary
| Method | Purpose |
| keys() | Returns all keys |
| values() | Returns all values |
| items() | Returns key-value pairs |
| get() | Retrieves a value |
| update() | Adds or updates entries |
| pop() | Removes a specified key |
| clear() | Removes all entries |
| copy() | Creates a shallow copy |
12. Looping Through Dictionaries
Loops allow us to process Dictionary information efficiently.
Imagine that a student record contains multiple details. Instead of printing every value individually, we can use a loop.
Consider:
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
12.1 Loop Through Keys
We can use a for loop to retrieve Dictionary keys.
Example:
for key in student:
print(key)
Output:
name age course
We can also use keys():
for key in student.keys():
print(key)
12.2 Loop Through Values
We can use the values() method to retrieve all values.
Example:
for value in student.values():
print(value)
Output:
Rahul 22 Python
12.3 Loop Through Keys and Values Together
The items() method is particularly useful when we want to access both the key and its corresponding value.
Example:
for key, value in student.items():
print(key, ":", value)
Output:
name : Rahul age : 22 course : Python
Let's understand this code.
- for starts the loop.
- key stores the current Dictionary key.
- value stores the corresponding value.
- student.items() provides key-value pairs.
- print() displays both pieces of information.
This approach is widely used when processing structured data.
13. Checking Whether a Key Exists
Sometimes we need to check whether a particular key is available before accessing its value.
Python provides the in operator for this purpose.
Example:
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
if "name" in student:
print("Student name exists")
else:
print("Student name not found")
Output:
Student name exists
Now let's check a missing key:
if "email" in student:
print("Email exists")
else:
print("Email not found")
Output:
Email not found
This technique helps prevent unnecessary errors when accessing Dictionary information.
14. Difference Between Sets and Dictionaries
Although Sets and Dictionaries both use curly braces, they serve different purposes.
| Feature | Set | Dictionary |
| Structure | Unique elements | Key-value pairs |
| Syntax | {10, 20, 30} | {"name": "Rahul"} |
| Duplicate handling | Removes duplicates | Keys must be unique |
| Access | No indexing | Access using keys |
| Mutable | Yes | Yes |
| Ordering | Unordered | Preserves insertion order |
| Main purpose | Manage unique data | Manage structured information |
| Empty creation | set() | {} |
When Should You Use Sets?
Use Sets when:
- You want to remove duplicate values.
- You need to find common elements.
- You want to compare two collections.
- You want to identify unique records.
When Should You Use Dictionaries?
Use Dictionaries when:
- You need to store related information.
- You want to access values using keys.
- You want to maintain structured records.
- You need to update specific information.
15. Real-World Applications of Sets and Dictionaries
Sets and Dictionaries are used in many types of software applications.
Application 1: Student Management Systems
A training institute can use Sets to maintain unique registration IDs.
Dictionaries can store student information such as name, age, course, city and email.
Application 2: Employee Management Systems
Dictionaries can store employee information, including:
- Employee ID
- Employee name
- Department
- Salary
- Joining date
Sets can help identify unique employee IDs.
Application 3: E-commerce Applications
An online shopping application can use Dictionaries to store product information.
Example:
product = {
"id": 101,
"name": "Laptop",
"price": 55000,
"category": "Electronics",
"stock": 15
}
print(product["name"])
print(product["price"])
Application 4: Website User Management
A website can maintain structured user information using Dictionaries.
Application 5: Removing Duplicate Data
Sets are useful when cleaning datasets that contain repeated values.
For example:
emails = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
]
unique_emails = set(emails)
print(unique_emails)
The Set keeps only unique email addresses.
16. Practical Project: Student Registration Management System
Now let's combine our learning and build a small practical project using Sets and Dictionaries.
Project Overview
We will create a simple Student Registration Management System.
The system will:
- Store unique student IDs.
- Maintain student information.
- Display student details.
- Update student information.
- Add new student information.
- Display updated records.
Step 1: Store Unique Student IDs
student_ids = {101, 102, 103, 101}
print("Student IDs:", student_ids)
Output:
Student IDs: {101, 102, 103}
Notice that the duplicate ID has been removed.
Step 2: Create Student Information
student = {
"id": 101,
"name": "Rahul",
"age": 22,
"course": "Python",
"city": "Ranchi"
}
print(student)
We created a Dictionary containing student information.
Step 3: Display Student Details
print("\nStudent Details:")
for key, value in student.items():
print(key, ":", value)
Output:
Student Details: id : 101 name : Rahul age : 22 course : Python city : Ranchi
Step 4: Update Student Information
Suppose Rahul has moved to another course.
We can update the information using:
student["age"] = 23 student["course"] = "Django" print(student)
Step 5: Add New Information
Now let's add the student's email address.
student["email"] = "[email protected]" print(student)
Step 6: Display Updated Student Details
print("\nUpdated Student Details:")
for key, value in student.items():
print(key, ":", value)
Output:
Updated Student Details: id : 101 name : Rahul age : 23 course : Django city : Ranchi email : [email protected]
Complete Project Code
Here is the complete program in one place:
# Student Registration Management System
# Store unique student IDs
student_ids = {101, 102, 103, 101}
print("Student IDs:", student_ids)
# Store student information
student = {
"id": 101,
"name": "Rahul",
"age": 22,
"course": "Python",
"city": "Ranchi"
}
# Display student details
print("\nStudent Details:")
for key, value in student.items():
print(key, ":", value)
# Update student information
student["age"] = 23
student["course"] = "Django"
# Add new information
student["email"] = "[email protected]"
# Display updated information
print("\nUpdated Student Details:")
for key, value in student.items():
print(key, ":", value)
What Did We Learn from This Project?
Through this project, we used:
- Sets to store unique student IDs.
- Dictionaries to maintain student information.
- items() to display key-value pairs.
- Assignment to update existing information.
- Assignment to add new information.
- For loops to process student records.
This is a basic example of how Python data structures can be used in application development.
17. Common Mistakes Beginners Should Avoid
While working with Sets and Dictionaries, beginners frequently make some mistakes.
Mistake 1: Creating an Empty Set Using {}
Incorrect:
my_set = {}
This creates an empty Dictionary.
Correct:
my_set = set()
Mistake 2: Accessing Set Elements Using Indexing
Incorrect:
numbers = {10, 20, 30}
print(numbers[0])
Sets do not support indexing.
Correct:
for number in numbers:
print(number)
Mistake 3: Using Duplicate Dictionary Keys
Example:
student = {
"name": "Rahul",
"name": "Aman"
}
print(student)
Output:
{'name': 'Aman'}
When duplicate keys are provided, the later value replaces the earlier value.
Mistake 4: Accessing Missing Dictionary Keys
Incorrect:
student = {
"name": "Rahul"
}
print(student["age"])
This raises a KeyError.
Safer alternative:
print(student.get("age", "Not Available"))
Mistake 5: Confusing add() and update()
- add() adds one element to a Set.
- update() adds elements from an iterable to a Set.
Mistake 6: Assuming Set Elements Have a Fixed Order
Sets are unordered. Their displayed order should not be relied upon.
Mistake 7: Using Mutable Objects as Set Elements
Lists and Dictionaries cannot be stored directly as Set elements because they are unhashable.
For example:
data = {[10, 20], [30, 40]}
This raises a TypeError.
18. Best Practices When Working with Sets and Dictionaries
Follow these practices when writing Python programs:
- Use meaningful variable names.
- Use Sets when duplicate values are not required.
- Use Dictionaries for structured information.
- Use get() when a key may not exist.
- Use items() when working with keys and values together.
- Avoid accessing Set elements through indexing.
- Use update() when adding or modifying multiple Dictionary entries.
- Check whether a key exists before performing operations when necessary.
- Keep your code organized and readable.
- Practice with real-world datasets.
19. Day 7 Learning Outcomes
After completing this tutorial, students should be able to:
- Understand Python Sets and Dictionaries.
- Create empty and non-empty Sets.
- Remove duplicate elements.
- Add and remove Set elements.
- Perform Union, Intersection, Difference and Symmetric Difference.
- Create Dictionaries using key-value pairs.
- Access Dictionary values using keys.
- Add and update Dictionary information.
- Remove Dictionary elements.
- Use important Dictionary methods.
- Loop through Dictionary records.
- Check whether a Dictionary key exists.
- Build a basic Student Registration Management System.
20. Frequently Asked Questions (FAQs)
1. What is a Set in Python?
A Set is a built-in data structure that stores unique elements. It automatically removes duplicate values.
2. What is a Dictionary in Python?
A Dictionary stores information in key-value pairs. It allows developers to access information using unique keys.
3. Does a Set allow duplicate values?
No. Sets automatically remove duplicate elements.
4. Can we access Set elements using indexing?
No. Sets do not support indexing or slicing because they are unordered collections.
5. How do you create an empty Set?
Use the set() constructor.
my_set = set()
6. What is the difference between {} and set()?
{} creates an empty Dictionary, whereas set() creates an empty Set.
7. What is the difference between add() and update()?
add() inserts one element into a Set, whereas update() inserts multiple elements from an iterable.
8. What is the difference between remove() and discard()?
Both remove elements from Sets. However, remove() raises a KeyError when an element does not exist, whereas discard() does not.
9. What is Union in Python Sets?
Union combines all unique elements from two Sets using the | operator or union() method.
10. What is Intersection in Python Sets?
Intersection returns the common elements between two Sets using the & operator or intersection() method.
11. What is Difference in Python Sets?
Difference returns elements present in the first Set but not in the second Set.
12. What is Symmetric Difference?
Symmetric Difference returns elements that exist in either Set but not in both.
13. Can Dictionary keys be duplicated?
No. Dictionary keys must be unique. If the same key appears multiple times, the later value replaces the earlier value.
14. Can Dictionary values be duplicated?
Yes. Different keys can contain the same value.
15. How do you access Dictionary values?
You can use square brackets or the get() method.
student["name"]
student.get("name")
16. What happens when we use get() with a missing key?
By default, get() returns None if the specified key does not exist. You can also provide a default value.
17. What is the purpose of the items() method?
The items() method returns key-value pairs, which are useful when looping through Dictionaries.
18. What is the difference between pop() and clear()?
pop() removes a specified key from a Dictionary, whereas clear() removes all entries.
19. Are Python Dictionaries ordered?
Yes. Python Dictionaries preserve insertion order.
20. Where are Sets and Dictionaries used in real-world applications?
Sets are useful for removing duplicates, finding common records and managing unique information. Dictionaries are useful for storing structured records such as student details, employee information, product data and customer records.



