# Dictionaries & Operations

> Explain Python dictionaries. What are common operations and patterns?

Canonical: https://www.internhack.in/learn/interview/python-interview/python-dictionaries
Last updated: 2026-11-28

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:

- O(1) average lookup, insertion, deletion
- Keys must be hashable (immutable): str, int, tuple, frozenset
- Values can be anything
- Since Python 3.7, dicts maintain insertion order (guaranteed)

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

- Dicts use ~50-70% more memory than lists due to hash table overhead
- Keys must be hashable: str, int, tuple are fine; list, dict, set are not
- Since Python 3.7, dict insertion order is guaranteed (was implementation detail in 3.6)

## Common follow-up questions

- How do hash collisions work in Python dicts?
- What is the difference between defaultdict and setdefault?
- How would you implement an LRU cache using OrderedDict?

## Interview tips

- Show you know Counter and defaultdict - they simplify many interview problems
- Always use .get() with defaults instead of try/except KeyError
- Mention that dicts maintain insertion order since 3.7

## Concepts covered

Dictionaries, Hash Maps, dict Methods, defaultdict, OrderedDict

Previous: [Lists, Tuples & Sets](https://www.internhack.in/learn/interview/python-interview/python-lists-tuples-sets) · Next: [Control Flow & Loops](https://www.internhack.in/learn/interview/python-interview/python-control-flow) · [All of Python Interview](https://www.internhack.in/learn/interview/python-interview)

## More Python Interview questions

- [Functions & Arguments](https://www.internhack.in/learn/interview/python-interview/python-functions)
- [\*args & kwargs](https://www.internhack.in/learn/interview/python-interview/python-args-kwargs)
- [List Comprehensions](https://www.internhack.in/learn/interview/python-interview/python-list-comprehensions)
- [Lambda, Map, Filter, Reduce](https://www.internhack.in/learn/interview/python-interview/python-lambda-map-filter)
- [OOP: Classes & Objects](https://www.internhack.in/learn/interview/python-interview/python-oop)
- [Inheritance & MRO](https://www.internhack.in/learn/interview/python-interview/python-inheritance-mro)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Python Interview](https://www.internhack.in/learn/interview/python-interview)
