Working with Dictionary and Set Methods
Course: Python Training
Topic: Working with Dictionary and Set Methods
Course Link: Python Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction
Python provides several built-in data structures for organizing, storing, and processing information. Dictionaries and sets are two important data structures used in everyday programming. Dictionaries store data as key-value pairs, while sets store unique elements without maintaining a positional index.
Dictionary and set methods allow developers to add, remove, retrieve, update, compare, and manipulate data efficiently. These operations are useful in data analysis, web development, automation, database applications, and problem-solving programs.
- Dictionary: A mutable mapping of unique keys to values.
- Set: A mutable collection of unique, hashable elements.
- Dictionary methods: Operations for managing keys and values.
- Set methods: Operations for managing unique elements and performing mathematical set operations.
2. Learning Objectives
After studying this topic, you will be able to:
- Understand dictionary and set structures.
- Create and manipulate dictionaries and sets.
- Use common dictionary methods such as
get(), update(), pop(), and items().
- Use set methods such as
add(), remove(), discard(), and union().
- Perform union, intersection, difference, and symmetric difference operations.
- Compare mutable sets with immutable frozensets.
- Remove duplicate values from collections.
- Apply dictionary and set methods to practical programming problems.
3. Understanding Dictionaries in Python
3.1 What Is a Dictionary?
A dictionary is a built-in Python data structure that stores information as key-value pairs. Each key identifies a value, allowing the value to be retrieved without searching through every element manually.
Dictionaries use curly braces {}, with a colon separating each key from its value.
student = {
"name": "Amit",
"age": 21,
"course": "Python",
"marks": 88
}
print(student)
Output:
{'name': 'Amit', 'age': 21, 'course': 'Python', 'marks': 88}
3.2 Characteristics of Dictionaries
- Dictionaries are mutable, so entries can be added, updated, or deleted.
- Each key must be unique.
- Keys must be hashable, such as strings, integers, or suitable tuples.
- Values can contain different data types, including lists and other dictionaries.
- Dictionaries preserve insertion order in modern Python.
- Dictionary keys are used to retrieve their associated values.
3.3 Creating a Dictionary
# Dictionary using curly braces
employee = {
"id": 101,
"name": "Priya",
"department": "IT"
}
# Empty dictionary
empty_data = {}
# Dictionary using dict()
product = dict(name="Laptop", price=55000)
print(employee)
print(empty_data)
print(product)
Output:
{'id': 101, 'name': 'Priya', 'department': 'IT'}
{}
{'name': 'Laptop', 'price': 55000}
4. Important Dictionary Methods
4.1 get() Method
The get() method retrieves a value associated with a key. If the key does not exist, it returns None by default or a specified fallback value.
student = {
"name": "Rahul",
"age": 22
}
print(student.get("name"))
print(student.get("marks"))
print(student.get("marks", 0))
Output:
Rahul
None
0
Use case: Use get() when a key may be missing and you want to avoid a KeyError.
4.2 keys() Method
The keys() method returns a dynamic view containing all dictionary keys.
employee = {
"name": "Priya",
"salary": 45000,
"department": "HR"
}
print(employee.keys())
Output:
dict_keys(['name', 'salary', 'department'])
4.3 values() Method
The values() method returns a dynamic view of all values in a dictionary.
prices = {
"Laptop": 55000,
"Mouse": 700,
"Keyboard": 1500
}
print(prices.values())
Output:
dict_values([55000, 700, 1500])
4.4 items() Method
The items() method returns a dynamic view of key-value pairs. It is commonly used to iterate over a dictionary.
student = {
"name": "Neha",
"age": 20,
"marks": 91
}
for key, value in student.items():
print(key, ":", value)
Output:
name : Neha
age : 20
marks : 91
4.5 update() Method
The update() method adds new entries and updates existing keys. It modifies the original dictionary and returns None.
student = {
"name": "Amit",
"age": 21
}
student.update({
"age": 22,
"course": "Python"
})
print(student)
Output:
{'name': 'Amit', 'age': 22, 'course': 'Python'}
4.6 pop() Method
The pop() method removes a specified key and returns its associated value. If the key is missing, it raises a KeyError unless a default value is provided.
student = {
"name": "Riya",
"age": 21,
"course": "Python"
}
removed_course = student.pop("course")
print(removed_course)
print(student)
Output:
Python
{'name': 'Riya', 'age': 21}
4.7 popitem() Method
The popitem() method removes and returns the last inserted key-value pair as a tuple.
data = {
"a": 10,
"b": 20,
"c": 30
}
print(data.popitem())
print(data)
Output:
('c', 30)
{'a': 10, 'b': 20}
4.8 setdefault() Method
The setdefault() method returns the value of an existing key. If the key is missing, it inserts the key with a specified default value and returns that value.
employee = {
"name": "Rahul",
"department": "IT"
}
employee.setdefault("city", "Mumbai")
employee.setdefault("department", "HR")
print(employee)
Output:
{'name': 'Rahul', 'department': 'IT', 'city': 'Mumbai'}
The department remains IT because the key already exists.
4.9 copy() Method
The copy() method creates a shallow copy of a dictionary. The outer dictionary is new, but nested mutable objects may still be shared.
original = {"name": "Amit", "marks": [80, 90]}
copied = original.copy()
copied["name"] = "Neha"
copied["marks"].append(95)
print(original)
print(copied)
Output:
{'name': 'Amit', 'marks': [80, 90, 95]}
{'name': 'Neha', 'marks': [80, 90, 95]}
4.10 clear() Method
The clear() method removes all entries from the dictionary.
data = {"name": "Amit", "age": 21}
data.clear()
print(data)
Output:
{}
4.11 Dictionary Methods Summary
| Method |
Purpose |
get() |
Retrieves a value with an optional default. |
keys() |
Returns a view of dictionary keys. |
values() |
Returns a view of dictionary values. |
items() |
Returns a view of key-value pairs. |
update() |
Adds or updates entries. |
pop() |
Removes a specified key and returns its value. |
popitem() |
Removes and returns the last inserted pair. |
setdefault() |
Returns a value or inserts a missing key. |
copy() |
Creates a shallow copy. |
clear() |
Removes all entries. |
5. Understanding Sets in Python
5.1 What Is a Set?
A set is a built-in Python data structure that stores unique, hashable elements. Sets are useful when you need to eliminate duplicate values, check membership, or perform mathematical operations such as union and intersection.
Sets use curly braces with comma-separated elements. An empty set must be created using set(), because {} creates an empty dictionary.
numbers = {10, 20, 30, 40}
colors = {"red", "green", "blue"}
empty_set = set()
print(numbers)
print(colors)
print(empty_set)
Note: Set elements have no positional indexing. Their displayed order should not be relied upon.
5.2 Characteristics of Sets
- Sets store unique elements and automatically eliminate duplicates.
- Sets are mutable, so elements can be added or removed.
- Set elements must be hashable.
- Sets do not support indexing or slicing.
- Sets support mathematical operations such as union, intersection, and difference.
- Sets are useful for membership testing and removing duplicate values.
5.3 Removing Duplicates Using a Set
numbers = [10, 20, 10, 30, 20, 40]
unique_numbers = set(numbers)
print(unique_numbers)
Output: The set contains 10, 20, 30, and 40. The order may vary.
To obtain a list containing unique values in their original first-occurrence order, use dict.fromkeys() instead:
numbers = [10, 20, 10, 30, 20, 40]
unique_numbers = list(dict.fromkeys(numbers))
print(unique_numbers)
Output:
[10, 20, 30, 40]
6. Important Set Methods
6.1 add() Method
The add() method inserts one element into a set. If the element already exists, the set remains unchanged.
fruits = {"apple", "banana"}
fruits.add("mango")
fruits.add("apple")
print(fruits)
Output: The set contains apple, banana, and mango, with no duplicates.
6.2 update() Method
The update() method adds elements from one or more iterables to a set. Duplicate elements are automatically ignored.
numbers = {1, 2, 3}
numbers.update([3, 4, 5])
numbers.update((5, 6))
print(numbers)
Output: The set contains 1, 2, 3, 4, 5, and 6. The order may vary.
6.3 remove() Method
The remove() method deletes a specified element. If the element does not exist, it raises a KeyError.
colors = {"red", "green", "blue"}
colors.remove("green")
print(colors)
Output: The set contains red and blue.
6.4 discard() Method
The discard() method removes an element if it exists. Unlike remove(), it does not raise an error if the element is missing.
numbers = {10, 20, 30}
numbers.discard(20)
numbers.discard(100)
print(numbers)
Output: The set contains 10 and 30.
6.5 pop() Method
The pop() method removes and returns an arbitrary element from a set. It raises a KeyError if the set is empty.
numbers = {10, 20, 30}
removed_value = numbers.pop()
print("Removed:", removed_value)
print("Remaining:", numbers)
Note: Do not assume which element will be removed. The selected element is not guaranteed to be the smallest or the first element displayed.
6.6 clear() Method
The clear() method removes all elements from a set.
numbers = {1, 2, 3, 4}
numbers.clear()
print(numbers)
Output:
set()
6.7 copy() Method
The copy() method returns a shallow copy of a set.
original = {10, 20, 30}
copied = original.copy()
copied.add(40)
print(original)
print(copied)
Output: The original set contains 10, 20, and 30. The copied set also contains 40.
6.8 Set Methods Summary
| Method |
Purpose |
add() |
Adds one element. |
update() |
Adds elements from one or more iterables. |
remove() |
Removes an element or raises a KeyError if missing. |
discard() |
Removes an element without raising an error if missing. |
pop() |
Removes and returns an arbitrary element. |
clear() |
Removes all elements. |
copy() |
Creates a shallow copy. |
7. Mathematical Set Operations
Python sets support mathematical operations for comparing and combining collections of unique elements.
7.1 Union
Union combines the elements of two sets, removing duplicates. It can be performed using | or the union() method.
A = {1, 2, 3}
B = {3, 4, 5}
print(A.union(B))
print(A | B)
Output: Both operations produce a set containing 1, 2, 3, 4, and 5.
7.2 Intersection
Intersection returns only the elements that exist in both sets. Use & or intersection().
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A.intersection(B))
print(A & B)
Output:
{3, 4}
7.3 Difference
Difference returns elements that exist in the first set but not in the second set. Use - or difference().
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A.difference(B))
print(A - B)
print(B - A)
Output:
{1, 2}
{1, 2}
{5, 6}
Difference is directional: A - B and B - A can produce different results.
7.4 Symmetric Difference
Symmetric difference returns elements that exist in either set but not in both. Use ^ or symmetric_difference().
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A.symmetric_difference(B))
print(A ^ B)
Output: The result contains 1, 2, 5, and 6.
7.5 Subset and Superset
A set is a subset of another set if all its elements are present in the other set. A set is a superset if it contains every element of the other set.
A = {1, 2}
B = {1, 2, 3, 4}
print(A.issubset(B))
print(B.issuperset(A))
print(A <= B)
print(B >= A)
Output:
True
True
True
True
7.6 Disjoint Sets
Two sets are disjoint when they have no elements in common. The isdisjoint() method checks this condition.
A = {1, 2, 3}
B = {4, 5, 6}
C = {3, 4, 5}
print(A.isdisjoint(B))
print(A.isdisjoint(C))
Output:
True
False
7.7 Set Operation Summary
| Operation |
Method |
Operator |
Meaning |
| Union |
union() |
| |
All elements from both sets. |
| Intersection |
intersection() |
& |
Elements common to both sets. |
| Difference |
difference() |
- |
Elements in the first set but not the second. |
| Symmetric difference |
symmetric_difference() |
^ |
Elements present in only one of the sets. |
| Subset |
issubset() |
<= |
Checks whether every element is in another set. |
| Superset |
issuperset() |
>= |
Checks whether a set contains every element of another set. |
| Disjoint |
isdisjoint() |
None |
Checks whether two sets have no common elements. |
8. Updating Sets with Mathematical Operations
Python also provides in-place methods that update the original set instead of creating a separate result.
8.1 update() and union_update Behavior
The set method update() adds elements from other iterables to the original set. It performs the equivalent of an in-place union.
A = {1, 2, 3}
B = {3, 4, 5}
A.update(B)
print(A)
Output: The updated set contains 1, 2, 3, 4, and 5.
8.2 intersection_update()
This method keeps only the elements shared with the supplied sets.
A = {1, 2, 3, 4}
B = {3, 4, 5}
A.intersection_update(B)
print(A)
Output:
{3, 4}
8.3 difference_update()
This method removes elements found in the supplied sets from the original set.
A = {1, 2, 3, 4}
B = {3, 4, 5}
A.difference_update(B)
print(A)
Output:
{1, 2}
8.4 symmetric_difference_update()
This method updates the original set to contain elements present in exactly one of the two sets.
A = {1, 2, 3}
B = {3, 4, 5}
A.symmetric_difference_update(B)
print(A)
Output: The updated set contains 1, 2, 4, and 5.
9. Frozensets: Immutable Sets
A frozenset is an immutable version of a set. It supports many mathematical set operations but does not allow elements to be added or removed after creation.
numbers = frozenset([1, 2, 3, 3])
print(numbers)
print(numbers.union({4, 5}))
print(numbers.intersection({2, 3, 4}))
Output: The original frozenset contains 1, 2, and 3. The union contains 1, 2, 3, 4, and 5; the intersection contains 2 and 3.
Frozensets are useful when a collection must remain immutable or when a set-like object needs to be used as a dictionary key or as an element of another set.
10. Comparing Dictionaries and Sets
| Feature |
Dictionary |
Set |
| Syntax |
{"name": "Amit"} |
{"Amit", "Priya"} |
| Stores |
Key-value pairs |
Unique elements |
| Duplicate keys/elements |
Keys are unique |
Elements are unique |
| Access |
Values retrieved by key |
Membership checked with in |
| Mutable |
Yes |
Yes |
| Indexing |
No positional indexing |
No positional indexing |
| Common methods |
get(), items(), update() |
add(), discard(), union() |
| Typical use |
Records, configurations, lookups |
Deduplication, membership, comparisons |
11. Practical Example: Student Records and Unique Subjects
This example combines dictionary operations with set operations to manage student information and identify unique subjects.
students = {
"S101": {
"name": "Amit",
"subjects": {"Python", "SQL", "Excel"}
},
"S102": {
"name": "Priya",
"subjects": {"Python", "Power BI", "SQL"}
},
"S103": {
"name": "Neha",
"subjects": {"Excel", "Python", "Statistics"}
}
}
# Access a dictionary value
print(students["S101"]["name"])
# Add a new subject to a student
students["S101"]["subjects"].add("Power BI")
# Update a student's details
students["S102"].update({"city": "Mumbai"})
# Find all unique subjects
all_subjects = set()
for details in students.values():
all_subjects.update(details["subjects"])
print("Unique Subjects:", all_subjects)
# Find subjects shared by the first two students
common_subjects = (
students["S101"]["subjects"]
& students["S102"]["subjects"]
)
print("Common Subjects:", common_subjects)
Explanation:
- The dictionary stores each student record.
- Each student's subjects are represented by a set.
- The
add() method adds a subject without creating duplicates.
- The dictionary
update() method adds a city field.
- The set
update() method combines subjects from different students.
- The intersection operator identifies common subjects.
12. Practical Example: Managing Website Visitors
Sets can track unique website visitors, while dictionaries can store details about each visitor.
visitors = {
"U101": {"name": "Amit", "city": "Mumbai"},
"U102": {"name": "Priya", "city": "Pune"},
"U103": {"name": "Rahul", "city": "Mumbai"}
}
today_visitors = {"U101", "U102", "U104"}
yesterday_visitors = {"U101", "U103"}
# Visitors who visited on both days
returning_visitors = today_visitors & yesterday_visitors
# Visitors who visited today for the first time
new_visitors = today_visitors - yesterday_visitors
# All unique visitors across both days
all_visitors = today_visitors | yesterday_visitors
print("Returning:", returning_visitors)
print("New Today:", new_visitors)
print("All Visitors:", all_visitors)
# Access visitor information when available
for visitor_id in returning_visitors:
if visitor_id in visitors:
print(visitors[visitor_id]["name"])
Explanation: The sets identify returning visitors, new visitors, and the combined visitor population. The dictionary provides additional information for visitor IDs that have corresponding records.
13. Common Errors and Troubleshooting
13.1 Using an Unhashable Object as a Set Element
# Invalid because lists are unhashable:
# data = {[1, 2], [3, 4]}
# Valid because tuples of integers are hashable:
data = {(1, 2), (3, 4)}
print(data)
Solution: Use hashable elements, such as strings, integers, or tuples containing hashable values.
13.2 Confusing an Empty Dictionary with an Empty Set
empty_dictionary = {}
empty_set = set()
print(type(empty_dictionary))
print(type(empty_set))
Output:
<class 'dict'>
<class 'set'>
Solution: Use set() to create an empty set.
13.3 Using remove() When an Element Might Be Missing
numbers = {10, 20, 30}
numbers.discard(50)
print(numbers)
Solution: Use discard() if the element may not exist. Use remove() when its presence is expected or should be enforced.
13.4 Expecting Set Elements to Remain in a Particular Order
colors = {"red", "green", "blue"}
for color in colors:
print(color)
Solution: Do not rely on the iteration order of a set. If sorted output is required and the elements are mutually comparable, use sorted(colors).
13.5 Accessing a Missing Dictionary Key
employee = {"name": "Priya"}
print(employee.get("salary", 0))
Solution: Use get() with a suitable default when a key may be missing.
13.6 Confusing Dictionary update() with Set update()
The dictionary update() method adds or replaces key-value pairs. The set update() method adds unique elements from an iterable.
# Dictionary update
employee = {"name": "Amit"}
employee.update({"salary": 40000})
# Set update
numbers = {1, 2}
numbers.update([2, 3, 4])
print(employee)
print(numbers)
Solution: Understand which data structure you are working with before choosing a method.
14. Best Practices
- Use dictionaries for records that require key-based access.
- Use sets when uniqueness and membership testing are important.
- Use
get() to safely retrieve potentially missing dictionary values.
- Use
items() to iterate over dictionary keys and values together.
- Use
discard() when removing a possibly missing set element.
- Use set operations to simplify comparisons between collections.
- Use
dict.fromkeys() carefully when assigning mutable default values.
- Do not depend on set iteration order.
- Use descriptive variable names for dictionaries and sets.
- Validate data before accessing deeply nested dictionary values.
- Prefer readable operations over unnecessarily complicated loops.
- Use a frozenset when an immutable set-like object is required.
15. Hands-On Practice Exercises
Exercise 1: Dictionary Methods
Create an employee dictionary with a name, age, department, and salary. Use get(), keys(), values(), and items() to display its contents.
Exercise 2: Updating Dictionary Values
Create a product dictionary. Update its price, add a category, remove an unnecessary field, and display the final dictionary.
Exercise 3: Set Creation and Modification
Create a set containing duplicate numbers. Add two new values, remove one existing value, and use discard() on a value that may be absent.
Exercise 4: Set Mathematical Operations
Create two sets representing students enrolled in Python and SQL. Find students enrolled in both courses, students enrolled only in Python, and all unique students.
Exercise 5: Dictionary and Set Combination
Create a dictionary containing student names and their subject sets. Find the complete list of unique subjects and identify subjects shared by two students.
Exercise 6: Unique Email Addresses
Given a list of email addresses containing duplicates, use a set to identify unique addresses. Display the number of unique addresses.
Exercise 7: Mini Project — Inventory Management
Create an inventory dictionary where each product ID maps to a product name, price, and quantity. Use dictionary methods to update inventory and sets to track unique product categories.
Your program should support:
- Adding new products.
- Updating existing product details.
- Removing products.
- Calculating total inventory value.
- Finding unique product categories.
- Identifying common categories between two suppliers.
16. Interview Questions and Answers
Q1. What is a dictionary in Python?
Answer: A dictionary is a mutable mapping that stores unique keys associated with values.
Q2. What is a set in Python?
Answer: A set is a mutable collection of unique, hashable elements used for membership testing and mathematical set operations.
Q3. What is the difference between get() and keys()?
Answer: get() retrieves the value associated with a specified key, while keys() returns a view of all dictionary keys.
Q4. What is the difference between remove() and discard() in sets?
Answer: Both remove an element, but remove() raises a KeyError if the element is absent, whereas discard() does not.
Q5. What does the union operation do?
Answer: Union combines elements from multiple sets and removes duplicates.
Q6. What does intersection return?
Answer: Intersection returns the elements shared by the specified sets.
Q7. What is the difference between a dictionary and a set?
Answer: A dictionary stores key-value pairs, while a set stores unique elements without associated values.
Q8. How do you remove duplicate values from a list?
Answer: Convert the list into a set to obtain unique elements. If original first-occurrence order must be preserved, use list(dict.fromkeys(values)) for hashable values.
Q9. What is a frozenset?
Answer: A frozenset is an immutable set that supports set operations but does not allow elements to be added or removed.
Q10. What is the purpose of dictionary update()?
Answer: It adds new key-value pairs and updates values for existing keys.
Q11. Can a set contain a list?
Answer: No. Lists are unhashable and cannot be elements of a set. A tuple of hashable elements may be used instead.
Q12. What is symmetric difference?
Answer: It returns the elements that occur in either set but not in both.
Q13. How do you check whether a dictionary contains a key?
Answer: Use the in operator, such as "name" in employee.
Q14. What does set pop() return?
Answer: It removes and returns an arbitrary element from a non-empty set.
Q15. What is the difference between update() and intersection_update() for sets?
Answer: update() adds elements from other iterables, while intersection_update() retains only elements common to the specified sets.
17. Quick Revision Checklist
- Dictionaries store key-value pairs.
- Dictionary keys must be unique and hashable.
get() retrieves values with an optional default.
keys(), values(), and items() return dictionary views.
update() adds or updates dictionary entries.
pop() removes a specified dictionary key.
- Sets store unique, hashable elements.
add() inserts one set element.
discard() safely removes a possibly missing element.
remove() raises an error if the element is absent.
- Union combines sets.
- Intersection finds common elements.
- Difference finds elements unique to the first set.
- Symmetric difference finds elements unique to either set.
- Frozensets are immutable.
- Sets do not support indexing or guarantee iteration order.
18. Conclusion
Dictionary and set methods are essential tools in Python programming. Dictionaries make it easy to organize and retrieve structured information, while sets provide an efficient way to manage unique values and compare collections.
By mastering methods such as get(), items(), update(), add(), discard(), and intersection(), you can write cleaner and more efficient programs. Combining dictionaries and sets also helps solve practical problems involving records, unique identifiers, inventory, enrollment lists, and data processing.
Regular practice with the examples and exercises in this lesson will prepare you for more advanced Python topics, including comprehensions, functions, data processing, and real-world application development.
19. Learn Python with JustAcademy
Continue developing your Python programming skills through the JustAcademy course resources.
Python Training Course: Explore Python Training at JustAcademy
Course Demo Registration: Register for a Course Demo
Official Website: Visit JustAcademy