Skip to content
beginner Phase 1 · Python Basics

Dictionaries & Sets

Work with dictionaries and sets for key-value storage and unique collections.

1h
0 problems
Topic Progress 0%

Dictionary Fundamentals

Creating Dictionaries

# Empty dict
empty = {}
empty = dict()

# Dict with values
person = {
    'name': 'Alice',
    'age': 30,
    'city': 'NYC'
}

# Using dict constructor
person = dict(name='Alice', age=30, city='NYC')

# From list of tuples
pairs = [('a', 1), ('b', 2), ('c', 3)]
dict_from_pairs = dict(pairs)
# {'a': 1, 'b': 2, 'c': 3}

# From two lists
keys = ['name', 'age']
values = ['Alice', 30]
person = dict(zip(keys, values))

Accessing Values

person = {'name': 'Alice', 'age': 30}

# Direct access (KeyError if missing)
name = person['name']

# Safe access with get()
age = person.get('age')        # 30
city = person.get('city', 'Unknown')  # 'Unknown'

# Check if key exists
if 'name' in person:
    print(person['name'])

Dictionary Methods

person = {'name': 'Alice', 'age': 30}

# Adding/updating
person['email'] = 'alice@example.com'  # Add new
person['age'] = 31                     # Update existing
person.update({'city': 'NYC', 'age': 32})  # Multiple

# Removing
del person['city']           # Remove key (KeyError if missing)
popped = person.pop('email') # Remove and return
person.pop('phone', None)    # Safe remove with default

# Information
len(person)               # 2
person.keys()             # dict_keys(['name', 'age'])
person.values()           # dict_values(['Alice', 31])
person.items()            # dict_items([('name', 'Alice'), ('age', 31)])

# Iteration
for key in person:
    print(f'{key}: {person[key]}')

for key, value in person.items():
    print(f'{key}: {value}')

Dictionary Complexity

Operation Average Worst
Access (get) O(1) O(n)
Insert O(1) O(n)
Delete O(1) O(n)
Search (in) O(1) O(n)
Iteration O(n) O(n)

Dictionary Comprehensions

Basic Syntax

# {key_expr: value_expr for item in iterable}
squares = {x: x**2 for x in range(6)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# With condition
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Inverting a Dictionary

original = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in original.items()}
# {1: 'a', 2: 'b', 3: 'c'}

# Handle duplicate values
original = {'a': 1, 'b': 1, 'c': 2}
inverted = {}
for k, v in original.items():
    inverted.setdefault(v, []).append(k)
# {1: ['a', 'b'], 2: ['c']}

Filtering and Transforming

# Filter by value
prices = {'apple': 1.0, 'banana': 0.5, 'cherry': 2.0}
expensive = {k: v for k, v in prices.items() if v > 1.0}
# {'cherry': 2.0}

# Transform values
prices_with_tax = {k: v * 1.1 for k, v in prices.items()}
# {'apple': 1.1, 'banana': 0.55, 'cherry': 2.2}

# Merge dictionaries (Python 3.9+)
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = dict1 | dict2  # {'a': 1, 'b': 3, 'c': 4}

Common Patterns

# Word frequency
def word_count(text):
    words = text.lower().split()
    counts = {}
    for word in words:
        counts[word] = counts.get(word, 0) + 1
    return counts

# Or using Counter
from collections import Counter
def word_count(text):
    return Counter(text.lower().split())

# Group by
def group_by(items, key_func):
    groups = {}
    for item in items:
        key = key_func(item)
        groups.setdefault(key, []).append(item)
    return groups

words = ['apple', 'banana', 'avocado', 'blueberry', 'cherry']
by_first = group_by(words, lambda w: w[0])
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

Sets

Creating Sets

# Empty set (NOT {} - that's a dict!)
empty = set()

# Set with values
fruits = {'apple', 'banana', 'cherry'}

# From list (removes duplicates)
numbers = list([1, 2, 2, 3, 3, 3])
unique = set(numbers)  # {1, 2, 3}

# Set comprehension
evens = {x for x in range(10) if x % 2 == 0}
# {0, 2, 4, 6, 8}

Set Operations

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

# Union (all elements)
A | B           # {1, 2, 3, 4, 5, 6, 7, 8}
A.union(B)      # Same

# Intersection (common elements)
A & B           # {4, 5}
A.intersection(B)  # Same

# Difference (elements in A not in B)
A - B           # {1, 2, 3}
A.difference(B) # Same

# Symmetric difference (elements in either, not both)
A ^ B           # {1, 2, 3, 6, 7, 8}
A.symmetric_difference(B)  # Same

Set Methods

s = {1, 2, 3}

# Adding
s.add(4)           # {1, 2, 3, 4}
s.update([5, 6])   # {1, 2, 3, 4, 5, 6}

# Removing
s.remove(3)        # KeyError if missing
s.discard(7)       # No error if missing
popped = s.pop()   # Remove and return arbitrary element
s.clear()          # Empty set

# Checking
3 in s             # True
s.issubset({1, 2, 3, 4})    # True
s.issuperset({1, 2})         # True
s.isdisjoint({4, 5})         # True (no common elements)

When to Use Sets

# Remove duplicates
names = ['Alice', 'Bob', 'Alice', 'Charlie']
unique_names = list(set(names))

# Fast membership testing
valid_ids = {1, 2, 3, 4, 5}
if user_id in valid_ids:  # O(1) vs O(n) for list
    process(user_id)

# Find common elements
friends_alice = {'Bob', 'Charlie', 'David'}
bob_bob = {'Alice', 'Charlie', 'Eve'}
mutual = friends_alice & friends_alice  # {'Charlie'}

# Find differences
all_users = {'Alice', 'Bob', 'Charlie', 'David', 'Eve'}
active_users = {'Alice', 'Charlie', 'Eve'}
inactive = all_users - active_users  # {'Bob', 'David'}

Frozen Sets

# Immutable sets
code = frozenset([1, 2, 3])

# Can be used as dictionary keys
locations = {
    frozenset(['NYC', 'Boston']): 'East Coast',
    frozenset(['LA', 'SF']): 'West Coast'
}