Paramclasses Academy - Blog

Tutorials Details

←
Post 12 of 20
→

Python Sets & Dictionaries: Methods, Operations & Examples

Python Sets & Dictionaries: Methods, Operations & Examples

October 17, 2026

Python Sets & Dictionaries: Methods, Operations & Examples

1. Introduction to Python Sets and Dictionaries

Python provides built-in data structures to store and organize collections of information. Two important data structures are Sets and Dictionaries.

A Set is an unordered collection of unique, hashable elements. It automatically removes duplicate values.

A Dictionary stores data as key-value pairs. Each key must be unique and hashable, while values can be of different data types.

Example

# Python Set
numbers = {10, 20, 30, 20}

# Python Dictionary
student = {
    "name": "Rahul",
    "age": 22,
    "course": "Python"
}

print(numbers)
print(student)

Output:

{10, 20, 30}
{'name': 'Rahul', 'age': 22, 'course': 'Python'}

The order in which set elements are displayed is not guaranteed. Dictionary insertion order is preserved in modern Python.

2. Python Sets

Sets are useful when you need to store unique values, remove duplicates, or compare collections.

Creating a Set

fruits = {"Apple", "Banana", "Mango"}
print(fruits)

The display order may vary because sets are unordered collections.

Duplicate Values

numbers = {1, 2, 3, 2, 1}

print(numbers)
print(len(numbers))

Output:

{1, 2, 3}
3

Only unique values remain in the set.

Creating an Empty Set

Use set() to create an empty set.

empty_set = set()
print(type(empty_set))

Output:

<class 'set'>

Important: {} creates an empty dictionary, not an empty set.

3. Adding and Removing Set Elements

add()

Adds one element to a set.

languages = {"Python", "Java"}

languages.add("PHP")

print(languages)

The set now contains Python, Java, and PHP; the display order may vary.

update()

Adds elements from one or more iterables.

numbers = {1, 2, 3}

numbers.update([3, 4, 5])

print(sorted(numbers))

Output:

[1, 2, 3, 4, 5]

remove()

Removes an element. If the element is missing, remove() raises a KeyError.

fruits = {"Apple", "Banana", "Mango"}

fruits.remove("Banana")

print("Banana" in fruits)

Output:

False

discard()

Removes an element if present. It does not raise an error if the element is missing.

numbers = {10, 20, 30}

numbers.discard(50)

print(sorted(numbers))

Output:

[10, 20, 30]

pop()

Removes and returns an arbitrary set element. It does not guarantee which element will be removed.

numbers = {10, 20, 30}

removed = numbers.pop()

print("Removed:", removed)
print("Remaining:", sorted(numbers))

The removed value may vary.

clear()

Removes all elements.

numbers = {1, 2, 3}

numbers.clear()

print(numbers)

Output:

set()

4. Set Operations

Python sets support mathematical operations for comparing collections.

Consider these two sets:

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

Union

Union returns all unique elements present in either set.

print(A | B)
print(A.union(B))

Output:

{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}

Intersection

Intersection returns elements common to both sets.

print(A & B)
print(A.intersection(B))

Output:

{3, 4}
{3, 4}

Difference

Difference returns elements present in the first set but not in the second.

print(A - B)
print(B - A)

Output:

{1, 2}
{5, 6}

Symmetric Difference

Returns elements present in either set, but not in both.

print(A ^ B)

Output:

{1, 2, 5, 6}

Note: Set output order is not guaranteed. Use sorted() when you need a predictable display for sortable values.

5. Checking Set Relationships

Python provides methods and operators to check how sets relate to each other.

issubset()

Checks whether every element of one set belongs to another set.

A = {1, 2}
B = {1, 2, 3, 4}

print(A.issubset(B))
print(A <= B)

Output:

True
True

issuperset()

Checks whether a set contains all elements of another set.

A = {1, 2, 3, 4}
B = {1, 2}

print(A.issuperset(B))

Output:

True

isdisjoint()

Returns True when two sets have no common elements.

A = {1, 2, 3}
B = {4, 5, 6}

print(A.isdisjoint(B))

Output:

True

These operations are useful for comparing categories, permissions, tags, and groups of users.

6. Removing Duplicates from a List

Sets provide a convenient way to remove duplicate values from a list.

numbers = [10, 20, 10, 30, 20, 40]

unique_numbers = set(numbers)

print(sorted(unique_numbers))

Output:

[10, 20, 30, 40]

If you need to preserve the original order, use dictionary keys:

numbers = [10, 20, 10, 30, 20, 40]

unique_numbers = list(dict.fromkeys(numbers))

print(unique_numbers)

Output:

[10, 20, 30, 40]

7. Looping Through Sets

Use a for loop to process set elements.

languages = {"Python", "PHP", "Java"}

for language in sorted(languages):
    print(language)

Output:

Java
PHP
Python

Sorting is used here to produce predictable output. Without sorting, set iteration order is not guaranteed.

8. Python Dictionaries

A dictionary stores information as key-value pairs.

Dictionaries are useful for representing student records, product details, employee information, settings, and API data.

Creating a Dictionary

student = {
    "name": "Rahul",
    "age": 22,
    "course": "Python",
    "marks": 85
}

print(student)

Accessing Values

student = {
    "name": "Rahul",
    "age": 22,
    "course": "Python"
}

print(student["name"])
print(student["age"])

Output:

Rahul
22

You can also use get() to safely retrieve a value.

print(student.get("course"))
print(student.get("city", "Not available"))

Output:

Python
Not available

Difference: Accessing a missing key with square brackets raises a KeyError; get() returns None or a supplied default value.

9. Adding and Updating Dictionary Items

Dictionaries are mutable, so you can add new keys and update existing values.

Adding a New Key

student = {"name": "Rahul", "age": 22}

student["city"] = "Raipur"

print(student)

Updating an Existing Value

student["age"] = 23

print(student["age"])

Output:

23

Using update()

student = {"name": "Rahul", "age": 22}

student.update({
    "age": 23,
    "course": "Python"
})

print(student)

Output:

{'name': 'Rahul', 'age': 23, 'course': 'Python'}

10. Removing Dictionary Items

pop()

Removes a specified key and returns its value.

student = {
    "name": "Rahul",
    "age": 22,
    "course": "Python"
}

removed_value = student.pop("age")

print(removed_value)
print(student)

Output:

22
{'name': 'Rahul', 'course': 'Python'}

popitem()

Removes and returns the last inserted key-value pair.

student = {"name": "Rahul", "age": 22}

item = student.popitem()

print(item)
print(student)

Output:

('age', 22)
{'name': 'Rahul'}

del

Deletes a specified key.

student = {"name": "Rahul", "age": 22}

del student["age"]

print(student)

clear()

Removes all dictionary items.

student = {"name": "Rahul", "age": 22}

student.clear()

print(student)

Output:

{}

11. Important Dictionary Methods

Method Purpose
get() Retrieves a value safely
keys() Returns a view of all keys
values() Returns a view of all values
items() Returns a view of key-value pairs
update() Adds or updates entries
pop() Removes a specified key
popitem() Removes the last inserted entry
setdefault() Retrieves a value or inserts a default
copy() Creates a shallow copy
clear() Removes all entries

Example

student = {
    "name": "Rahul",
    "age": 22,
    "course": "Python"
}

print(list(student.keys()))
print(list(student.values()))
print(list(student.items()))

Output:

['name', 'age', 'course']
['Rahul', 22, 'Python']
[('name', 'Rahul'), ('age', 22), ('course', 'Python')]

12. Looping Through Dictionaries

Loop Through Keys

student = {
    "name": "Rahul",
    "age": 22,
    "course": "Python"
}

for key in student:
    print(key)

Loop Through Values

for value in student.values():
    print(value)

Loop Through Keys and Values

Use items() to access both keys and values.

for key, value in student.items():
    print(f"{key}: {value}")

Output:

name: Rahul
age: 22
course: Python

13. Checking Whether a Key Exists

Use the in operator to check whether a dictionary contains a key.

student = {
    "name": "Rahul",
    "age": 22
}

print("name" in student)
print("city" in student)

Output:

True
False

For dictionaries, in checks keys, not values.

To check values, use:

print("Rahul" in student.values())

Output:

True

14. Nested Dictionaries

A nested dictionary contains another dictionary as a value. It is useful for storing structured records.

Example

students = {
    "student1": {
        "name": "Rahul",
        "marks": 85
    },
    "student2": {
        "name": "Priya",
        "marks": 92
    }
}

print(students["student1"]["name"])
print(students["student2"]["marks"])

Output:

Rahul
92

Loop Through a Nested Dictionary

for student_id, details in students.items():
    print(f"ID: {student_id}")
    print(f"Name: {details['name']}")
    print(f"Marks: {details['marks']}")

This structure is useful for student management systems and similar applications.

15. Dictionary Comprehension

Dictionary comprehension creates a dictionary using a concise expression.

Syntax

{key_expression: value_expression for item in iterable}

Example 1: Create Squares

squares = {number: number ** 2 for number in range(1, 6)}

print(squares)

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Example 2: Filter Dictionary Values

marks = {
    "Rahul": 85,
    "Amit": 35,
    "Priya": 92,
    "Neha": 28
}

passed = {
    name: score
    for name, score in marks.items()
    if score >= 40
}

print(passed)

Output:

{'Rahul': 85, 'Priya': 92}

16. Practical Project: Student Marks Manager

This program stores student marks in a dictionary and displays each student's result.

students = {
    "Rahul": 85,
    "Amit": 35,
    "Priya": 92,
    "Neha": 68
}

passing_marks = 40

for name, marks in students.items():
    status = "Pass" if marks >= passing_marks else "Fail"
    print(f"Student: {name:<10} Marks: {marks:>3} Status: {status}")

average = sum(students.values()) / len(students)

print(f"Class Average: {average:.2f}")

Output:

Student: Rahul      Marks:  85 Status: Pass
Student: Amit       Marks:  35 Status: Fail
Student: Priya      Marks:  92 Status: Pass
Student: Neha       Marks:  68 Status: Pass
Class Average: 70.00

This project demonstrates dictionary storage, iteration, conditions, and calculations.

17. Practical Project: Product Inventory Manager

This project stores product names and their stock quantities in a dictionary.

inventory = {
    "Keyboard": 10,
    "Mouse": 15,
    "Monitor": 5
}

product = input("Enter product name: ").strip().title()
quantity = int(input("Enter quantity to add: "))

if quantity < 0:
    print("Quantity cannot be negative.")
else:
    inventory[product] = inventory.get(product, 0) + quantity

    print("\nUpdated Inventory")

    for name, stock in inventory.items():
        print(f"{name:<12}: {stock}")

Sample Input:

Enter product name: keyboard
Enter quantity to add: 5

Output:

Updated Inventory
Keyboard    : 15
Mouse       : 15
Monitor     : 5

This example demonstrates a basic inventory update. A production application would also need stronger input validation and persistent storage.

18. Practical Project: Find Common Interests

Use sets to identify common interests between two users.

user1 = {"Python", "Web Development", "Gaming", "Movies"}
user2 = {"Python", "Gaming", "Music", "Photography"}

common = user1 & user2
all_interests = user1 | user2

print("Common Interests:", sorted(common))
print("All Unique Interests:", sorted(all_interests))

Output:

Common Interests: ['Gaming', 'Python']
All Unique Interests: ['Gaming', 'Movies', 'Music', 'Photography', 'Python', 'Web Development']

This approach can be useful for recommendation systems, tags, and category matching.

19. Common Mistakes

Mistake 1: Creating an Empty Set Incorrectly

data = {}
print(type(data))

Output: <class 'dict'>

Correct approach:

data = set()
print(type(data))

Mistake 2: Using an Unhashable Value in a Set

Lists and dictionaries cannot be set elements because they are unhashable.

# This raises a TypeError
data = {[1, 2], [3, 4]}

Use tuples instead when their elements are hashable:

data = {(1, 2), (3, 4)}
print(data)

Mistake 3: Accessing a Missing Dictionary Key

student = {"name": "Rahul"}
print(student["age"])

This raises a KeyError.

Safer approach:

print(student.get("age", "Not available"))

Mistake 4: Assuming Sets Preserve Order

Sets are unordered collections. Do not depend on the display order. Use sorted() when predictable output is required and the values can be compared.

Mistake 5: Confusing Dictionary Keys and Values

student = {"name": "Rahul"}

print("Rahul" in student)

Output: False

The in operator checks keys by default.

Correct approach:

print("Rahul" in student.values())

Output: True

20. Practice Programs

Try solving these exercises:

  1. Create a set of five programming languages.

  2. Remove duplicate values from a list using a set.

  3. Add and remove set elements.

  4. Find the union of two sets.

  5. Find the intersection of two sets.

  6. Find the difference between two sets.

  7. Check whether one set is a subset of another.

  8. Create a dictionary containing a student's name, age, and course.

  9. Add a new key to a dictionary.

  10. Update and delete dictionary entries.

  11. Print all keys and values using dictionary methods.

  12. Count the frequency of characters in a string using a dictionary.

  13. Create a nested dictionary for multiple students.

  14. Generate a dictionary of squares using comprehension.

  15. Build a product inventory manager.

  16. Build a student marks manager.

  17. Find common interests between two users.

  18. Count the frequency of words in a sentence.

  19. Display products whose stock is below a chosen threshold.

  20. Build a simple contact book using a dictionary.

21. Quiz: Test Your Knowledge

Q1. What is a Python set?

Answer: An unordered collection of unique, hashable elements.

Q2. How do you create an empty set?

Answer: set().

Q3. Which operator performs set union?

Answer: |.

Q4. Which operator performs set intersection?

Answer: &.

Q5. What is a dictionary?

Answer: A collection that stores key-value pairs.

Q6. Which method safely retrieves a dictionary value with a default?

Answer: get().

Q7. What does keys() return?

Answer: A view of the dictionary's keys.

Q8. What does items() return?

Answer: A view of the dictionary's key-value pairs.

Q9. Does the in operator check dictionary keys or values by default?

Answer: Keys.

Q10. What is dictionary comprehension?

Answer: A concise way to create a dictionary from an iterable or another collection.

22. Assignment

Build a Student and Inventory Management Program with two sections.

Section A: Student Manager

  1. Store student names and marks in a dictionary.

  2. Display each student's result.

  3. Calculate the class average.

  4. Find students who passed and failed.

  5. Allow the user to search for a student's marks.

Section B: Inventory Manager

  1. Store product names and stock quantities in a dictionary.

  2. Allow users to add stock.

  3. Allow users to search for a product.

  4. Display products with low stock.

  5. Use a set to remove duplicate product tags.

  6. Display unique tags and common tags between two product groups.

Use dictionaries, sets, loops, conditions, methods, and input validation to complete the assignment.

23. Summary

In this tutorial, you learned:

  • How to create sets and dictionaries.

  • Adding, updating, and removing set elements.

  • Set union, intersection, difference, and symmetric difference.

  • Subset, superset, and disjoint checks.

  • Removing duplicate values from lists.

  • Creating, accessing, updating, and deleting dictionary entries.

  • Important dictionary methods such as get(), keys(), values(), items(), and update().

  • Looping through dictionaries and checking keys.

  • Nested dictionaries and dictionary comprehension.

  • Practical student, inventory, and common-interest projects.

  • Common mistakes, practice programs, quizzes, and assignments.

Conclusion: Sets are ideal for working with unique values and comparing collections, while dictionaries are useful for storing structured key-value data. Understanding both data structures will help you write clearer and more efficient Python programs.

←
Post 12 of 20
→