Dictionaries & Sets
Key-value storage and unique collections
Skills taught: python.dict, python.set, python.dict-comprehension
Dictionaries
# Create a dictionary
person = {
'name': 'Prashant',
'age': 28,
'city': 'Delhi'
}
# Access values
print(person['name']) # Prashant
print(person.get('age')) # 28
print(person.get('email', 'N/A')) # N/A (default)
# Add and update
person['email'] = 'p@example.com'
person['age'] = 29
# Delete
del person['city']
removed = person.pop('email') # removes and returns
# Check existence
print('name' in person) # True
print('phone' in person) # False
# Iterate
for key in person:
print(key)
for key, value in person.items():
print(f'{key}: {value}')
print(list(person.keys())) # ['name', 'age']
print(list(person.values())) # ['Prashant', 29]
Nested dicts and dict comprehensions
# Nested dict (like JSON)
user = {
'name': 'Prashant',
'address': {'city': 'Delhi', 'pin': '110001'},
'scores': [95, 82, 78]
}
print(user['address']['city']) # Delhi
# Dict comprehension
names = ['Alice', 'Bob', 'Charlie']
scores = [95, 82, 78]
score_map = {name: score for name, score in zip(names, scores)}
print(score_map) # {'Alice': 95, 'Bob': 82, 'Charlie': 78}
# Count occurrences
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts) # {'apple': 3, 'banana': 2, 'cherry': 1}
# Easier with Counter
from collections import Counter
print(Counter(words)) # same result
Sets
# Create a set
colors = {'red', 'blue', 'green'}
nums = set([1, 2, 3, 2, 1]) # duplicates removed
print(nums) # {1, 2, 3}
# Add and remove
colors.add('yellow')
colors.discard('purple') # no error if not found
colors.remove('red') # raises KeyError if not found
# Membership test — O(1), much faster than list!
print('blue' in colors) # True
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union: {1,2,3,4,5,6}
print(a & b) # intersection: {3,4}
print(a - b) # difference: {1,2} (in a but not b)
print(a ^ b) # symmetric diff: {1,2,5,6}
# Remove duplicates from a list
with_dups = [1, 2, 3, 2, 1, 4]
unique = list(set(with_dups))
print(unique) # [1, 2, 3, 4] (order may vary)
Frequently Asked Questions
What is the difference between dict.pop() and del dict[key]?
del dict[key] removes the key (raises KeyError if not present). dict.pop(key) removes and RETURNS the value (also raises KeyError if not present). dict.pop(key, default) safely removes and returns a default if key is absent.
Can I use a list as a dictionary key?
No. Dict keys must be hashable (immutable). Lists are mutable, so they can't be hashed. Use a tuple instead: d[(1, 2)] = 'point'. Strings, ints, floats, tuples, and frozensets are all valid keys.