Session-10 : Dictionaries in Python –from lists,
tuples and Key-Value Power!.
✅ Learning Objectives
- Understand
what sets are in Python.
- Learn
how sets differ from lists and tuples.
- Explore
set operations (union, intersection, difference, symmetric
difference).
- Work
with set methods like add(), remove(), discard(), update().
- Understand
immutability with frozenset.
π Key Concepts
- Definition:
A set is an unordered collection of unique elements in Python.
Example:
Python
my_set = {1, 2, 3, 3} # Output: {1, 2, 3}
Show more lines
- Why
Sets?
- Automatically
removes duplicates.
- Faster
membership testing (in operator).
- Useful
for mathematical operations.
- Creating
Sets:
Python
s1 = {1, 2, 3}
s2 = set([4, 5, 6])
empty_set = set() # {} creates a dictionary, not a set
Show more lines
- Common
Operations:
Python
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union: {1, 2, 3, 4, 5}
print(a & b) # Intersection: {3}
print(a - b) # Difference: {1, 2}
print(a ^ b) # Symmetric Difference: {1, 2, 4, 5}
Show more lines
- Methods:
- add(),
remove(), discard(), pop(), clear()
- update()
for merging sets.
- frozenset:
- Immutable
version of a set.
Python
fs = frozenset([1, 2, 3])
Show more lines
π Practice Ideas
- Remove
duplicates from a list using a set.
- Find
common elements between two lists.
- Write
a program to check if two sets are disjoint.
- Implement
a simple set-based membership system.
Key-Value Power
Learning Objectives
- Understand
what dictionaries are and why they are useful.
- Learn
how to create, access, and modify dictionary elements.
- Explore
dictionary methods like get(), keys(), values(), items(), update().
- Understand
nested dictionaries and dictionary comprehensions.
π Key Concepts
- Definition:
A dictionary is an unordered collection of key-value pairs.
Example:
Python
my_dict = {"name": "Hitesh",
"role": "Engineer"}
Show more lines
- Creating
Dictionaries:
Python
d1 = {"a": 1, "b": 2}
d2 = dict(x=10, y=20)
empty_dict = {}
Show more lines
- Accessing
& Modifying:
Python
print(d1["a"]) # 1
print(d1.get("c")) # None
d1["b"] = 5 # Modify value
d1["c"] = 3 # Add new key-value
Show more lines
- Common
Methods:
- keys(),
values(), items()
- update(),
pop(), clear()
- Dictionary
Comprehension:
Python
squares = {x: x**2 for x in range(5)}
Show more lines
- Nested
Dictionaries:
Python
student = {
"name": "Hitesh",
"marks": {"math": 90,
"science": 85}
Show more lines
π Practice Ideas
- Count
word frequency in a sentence using a dictionary.
- Merge
two dictionaries.
- Create
a dictionary from two lists (keys and values).
- Implement
a simple phonebook using a dictionary.
No comments:
Post a Comment