BeginnerPython ยท Lesson 8

Dictionaries and Sets

Work with Python's key-value dictionaries and unique-element sets

Dictionaries

Dictionaries store key-value pairs. Keys must be unique and hashable.

# Creating dicts
empty = {}
person = {"name": "Alice", "age": 30, "city": "NYC"}
d = dict(name="Bob", age=25)
from_pairs = dict([("a", 1), ("b", 2)])

# Type check
print(type(person))  # <class 'dict'>

Accessing and Modifying

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

# Access
print(person["name"])          # Alice
print(person.get("age"))       # 30
print(person.get("job", "N/A"))# N/A (default if key missing)

# Modify
person["age"] = 31              # update existing
person["email"] = "a@b.com"    # add new key

# Delete
del person["email"]
removed = person.pop("age")    # returns removed value
person.clear()                  # empty the dict

Dictionary Methods

d = {"a": 1, "b": 2, "c": 3}

print(d.keys())    # dict_keys(['a', 'b', 'c'])
print(d.values())  # dict_values([1, 2, 3])
print(d.items())   # dict_items([('a', 1), ('b', 2), ('c', 3)])

# Iteration
for key in d:
    print(key, d[key])

for key, value in d.items():
    print(f"{key} โ†’ {value}")

# Merge dicts
d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "b": 99}
merged = {**d1, **d2}        # {'a':1, 'b':99, 'c':3} โ€” d2 wins
d1.update(d2)                # in-place merge

Dictionary Comprehensions

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

filtered = {k: v for k, v in squares.items() if v > 9}
# {4: 16, 5: 25}

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

defaultdict and Counter

from collections import defaultdict, Counter

# defaultdict โ€” no KeyError on missing keys
word_count = defaultdict(int)
words = "the cat sat on the mat the cat".split()
for word in words:
    word_count[word] += 1
print(dict(word_count))

# Counter โ€” counts hashable items
counter = Counter(words)
print(counter.most_common(2))  # [('the', 3), ('cat', 2)]

Sets

Sets are unordered collections of unique elements.

# Creating sets
empty = set()                # NOT {} โ€” that creates an empty dict!
numbers = {1, 2, 3, 4, 5}
from_list = set([1, 2, 2, 3, 3, 3])  # {1, 2, 3} โ€” duplicates removed

print(type(numbers))  # <class 'set'>

Set Operations

a = {1, 2, 3, 4, 5}
b = {3, 4, 5, 6, 7}

print(a | b)   # {1,2,3,4,5,6,7}  โ€” union
print(a & b)   # {3,4,5}          โ€” intersection
print(a - b)   # {1,2}            โ€” difference (in a, not in b)
print(a ^ b)   # {1,2,6,7}        โ€” symmetric difference

# Methods
a.add(6)
a.remove(1)           # raises KeyError if missing
a.discard(99)         # safe remove (no error if missing)
a.update({10, 11})    # add multiple

# Subset and superset
{1, 2}.issubset({1, 2, 3})    # True
{1, 2, 3}.issuperset({1, 2})  # True
{1, 2}.isdisjoint({3, 4})     # True (no common elements)

Frozensets

Immutable sets (can be dict keys or set elements):

fs = frozenset([1, 2, 3])
d = {fs: "immutable set as key!"}

Exercises

Exercise 1: Word Frequency

Count the frequency of each character in "abracadabra".

Solution:

from collections import Counter
freq = Counter("abracadabra")
print(freq.most_common())
# [('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]

Exercise 2: Anagram Check

Two words are anagrams if they contain the same characters. Check if "listen" and "silent" are anagrams.

Solution:

def is_anagram(s1, s2):
    return sorted(s1.lower()) == sorted(s2.lower())
    # OR: Counter(s1) == Counter(s2)

print(is_anagram("listen", "silent"))  # True
print(is_anagram("hello", "world"))    # False

Exercise 3: Group By

Given a list of words, group them by their first letter using a defaultdict.

Solution:

from collections import defaultdict
words = ["apple", "banana", "avocado", "blueberry", "cherry", "apricot"]
grouped = defaultdict(list)
for word in words:
    grouped[word[0]].append(word)

for letter, group in sorted(grouped.items()):
    print(f"{letter}: {group}")
# a: ['apple', 'avocado', 'apricot']
# b: ['banana', 'blueberry']
# c: ['cherry']

Exercise 4: Set Operations

Find names that appear in list A but NOT in list B.

Solution:

a = {"Alice", "Bob", "Carol", "Dave"}
b = {"Bob", "Dave", "Eve"}
only_in_a = a - b
print(only_in_a)  # {'Alice', 'Carol'}