Dictionaries & Operations

Difficulty: Beginner

Question

Explain Python dictionaries. What are common operations and patterns?

Answer

Dictionaries are Python's built-in hash map implementation - unordered (insertion-ordered since 3.7) collections of key-value pairs.

Key characteristics:

Dictionaries are one of the most used data structures in Python and power many internal mechanisms (namespaces, class attributes).

Code examples

Common Dict Operations

user = {'name': 'Alice', 'age': 30, 'role': 'Engineer'}

# Access
print(user['name'])           # 'Alice'
print(user.get('salary', 0))  # 0 (default if missing)

# Modify
user['age'] = 31              # Update
user['salary'] = 80000        # Add new key
del user['role']               # Delete key

# Iteration
for key, value in user.items():
    print(f"{key}: {value}")

# Merging (Python 3.9+)
defaults = {'theme': 'dark', 'lang': 'en'}
prefs = {'theme': 'light', 'font': 14}
merged = defaults | prefs  # prefs overrides defaults
print(merged)

# Dictionary unpacking
merged2 = {defaults, prefs}  # Same result, works in 3.5+
print(merged2)

Use .get() with a default instead of [] to avoid KeyError. The | merge operator (3.9+) is cleaner than {a, b}.

Dict Comprehensions & Patterns

# Dict comprehension
squares = {x: x2 for x in range(6)}
print(squares)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

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

# Count word frequency
words = "the cat sat on the mat the cat".split()
freq = {}
for w in words:
    freq[w] = freq.get(w, 0) + 1
print(freq)  # {'the': 3, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1}

# setdefault: get or set if missing
graph = {}
graph.setdefault('A', []).append('B')
graph.setdefault('A', []).append('C')
print(graph)  # {'A': ['B', 'C']}

Dict comprehensions are concise for transformations. setdefault() combines get-or-create in one call, perfect for building adjacency lists.

defaultdict and Counter

from collections import defaultdict, Counter

# defaultdict: auto-creates missing keys
word_groups = defaultdict(list)
words = ["apple", "banana", "avocado", "blueberry", "cherry"]
for word in words:
    word_groups[word[0]].append(word)
print(dict(word_groups))

# Counter: count occurrences
text = "abracadabra"
counts = Counter(text)
print(counts)              # Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
print(counts.most_common(2))  # [('a', 5), ('b', 2)]

# Counter arithmetic
c1 = Counter(a=3, b=1)
c2 = Counter(a=1, b=2)
print(c1 + c2)  # Counter({'a': 4, 'b': 3})
print(c1 - c2)  # Counter({'a': 2})

defaultdict eliminates the need for key-existence checks. Counter is a specialized dict for counting hashable objects.

Key points

Common follow-up questions

Interview tips

Concepts covered

Dictionaries, Hash Maps, dict Methods, defaultdict, OrderedDict

More Python Interview questions