Python 3 — Dictionaries & Sets
Dictionaries store key-value pairs — like a real dictionary where you look up a word (key) to find its definition (value). Sets are unordered collections of unique items. Together they give you powerful ways to organize and query data efficiently.
1 Creating & Accessing Dictionaries
Python 3 — Dictionary Basics▶ Run Code
# Creating a dictionary
student = {
"name": "Balaji",
"age": 25,
"grade": "A",
"subjects": ["Math", "Python", "DSA"]
}
# Accessing by key
print(student["name"]) # Balaji
print(student["age"]) # 25
print(student["subjects"]) # ['Math', 'Python', 'DSA']
# .get() — safe access (returns None if key missing)
print(student.get("email")) # None
print(student.get("email", "N/A")) # N/A (default value)
# Check if key exists
print("grade" in student) # True
print("phone" in student) # False
2 Modifying Dictionaries
Python 3 — Modify Dict▶ Run Code
profile = {"name": "Alice", "age": 30}
# Add new key-value
profile["email"] = "alice@example.com"
profile["city"] = "Hyderabad"
print(profile)
# Update existing value
profile["age"] = 31
print(profile["age"]) # 31
# Update multiple keys at once
profile.update({"age": 32, "phone": "9876543210"})
print(profile)
# Remove keys
del profile["phone"] # Remove by key
removed = profile.pop("city") # Remove & return
print(f"Removed: {removed}")
# Clear all
temp = {"a": 1, "b": 2}
temp.clear()
print(temp) # {}
3 Iterating Dictionaries
Python 3 — Dict Iteration▶ Run Code
inventory = {
"apples": 50,
"bananas": 30,
"oranges": 75,
"mangoes": 20
}
# Iterate keys (default)
for fruit in inventory:
print(fruit)
# Iterate keys explicitly
for key in inventory.keys():
print(key)
# Iterate values
for quantity in inventory.values():
print(quantity)
# Iterate key-value pairs (most useful!)
for fruit, qty in inventory.items():
status = "✅ In Stock" if qty > 25 else "⚠️ Low Stock"
print(f"{fruit}: {qty} units — {status}")
4 Dictionary Methods
| Method | Description |
|---|---|
.keys() | Returns all keys |
.values() | Returns all values |
.items() | Returns (key, value) pairs |
.get(k, default) | Safe access with fallback |
.update(d) | Merge another dict |
.pop(k) | Remove & return value |
.setdefault(k, v) | Set only if key missing |
Python 3 — Dict Methods▶ Run Code
scores = {"Alice": 92, "Bob": 78}
# setdefault — adds only if key doesn't exist
scores.setdefault("Charlie", 85)
scores.setdefault("Alice", 0) # Alice already exists, not changed
print(scores) # {'Alice': 92, 'Bob': 78, 'Charlie': 85}
# Merge dicts (Python 3.9+)
extra = {"Diana": 95, "Eve": 88}
all_scores = scores | extra
print(all_scores)
# Count word frequency
text = "the cat sat on the mat the cat"
word_freq = {}
for word in text.split():
word_freq[word] = word_freq.get(word, 0) + 1
print(word_freq)
5 Nested Dictionaries
Python 3 — Nested Dicts▶ Run Code
company = {
"name": "TechCorp",
"employees": {
"E001": {"name": "Alice", "role": "Developer", "salary": 80000},
"E002": {"name": "Bob", "role": "Designer", "salary": 70000},
"E003": {"name": "Carol", "role": "Manager", "salary": 90000}
}
}
# Access nested values
print(company["name"]) # TechCorp
print(company["employees"]["E001"]["name"]) # Alice
print(company["employees"]["E002"]["salary"]) # 70000
# Iterate nested dict
for emp_id, info in company["employees"].items():
print(f"{emp_id}: {info['name']} ({info['role']}) — ₹{info['salary']:,}")
6 Python Sets
Sets are unordered collections of unique values. Great for deduplication and membership tests:
Python 3 — Sets▶ Run Code
# Creating sets
fruits = {"apple", "banana", "cherry", "apple", "banana"}
print(fruits) # Only unique: {'apple', 'banana', 'cherry'}
# Add and remove
fruits.add("mango")
fruits.discard("cherry") # No error if not found
print(fruits)
# Fast membership test
print("apple" in fruits) # True (faster than list!)
print("grape" in fruits) # False
# Set operations
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
print(a | b) # Union: {1,2,3,4,5,6,7,8}
print(a & b) # Intersection: {4,5}
print(a - b) # Difference: {1,2,3}
print(a ^ b) # Symmetric diff: {1,2,3,6,7,8}
7 Dict Comprehensions
Python 3 — Dict Comprehension▶ Run Code
# Basic dict comprehension: {key: value for item in iterable}
squares = {n: n**2 for n in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# With condition: word → length (only long words)
words = ["Python", "is", "an", "amazing", "language"]
long_words = {w: len(w) for w in words if len(w) > 3}
print(long_words) # {'Python': 6, 'amazing': 7, 'language': 8}
# Invert a dictionary (swap keys and values)
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
8 Coding Challenge
Build a simple student grade book:
- Create a dictionary with 5 students and their list of 3 test scores each
- Calculate the average score for each student
- Determine their grade (A ≥ 90, B ≥ 80, C ≥ 70, F otherwise)
- Store results as:
{"Alice": {"avg": 87.3, "grade": "B"}} - Find the top performer (highest average) and print their details
- Use a set to find which students scored 90+ in at least one test