Out of every built-in data structure Python offers, the dictionary is probably the one I reach for the most in real projects. Once I understood how dictionaries work internally — as hash tables offering near-instant lookups — a huge amount of code I used to write with nested loops suddenly became simpler and faster. In this guide, I want to cover Python dictionaries from the ground up: how to create them, manipulate them, and understand what’s actually happening under the hood when I use one.
What Is a Dictionary?
A dictionary in Python is an unordered (well, actually insertion-ordered since Python 3.7) collection of key-value pairs, where each key must be unique and hashable, and values can be anything.
person = {"name": "Ahmed", "age": 30, "city": "Lahore"}
print(person)
Output:
{'name': 'Ahmed', 'age': 30, 'city': 'Lahore'}
Creating Dictionaries
There are several ways I create dictionaries depending on the situation:
# Literal syntax
d1 = {"a": 1, "b": 2}
# Using dict() with keyword arguments
d2 = dict(a=1, b=2)
# From a list of tuples
d3 = dict([("a", 1), ("b", 2)])
# Dictionary comprehension
d4 = {k: v for k, v in [("a", 1), ("b", 2)]}
print(d1, d2, d3, d4)
Output:
{'a': 1, 'b': 2} {'a': 1, 'b': 2} {'a': 1, 'b': 2} {'a': 1, 'b': 2}
Accessing and Modifying Values
person = {"name": "Ahmed", "age": 30}
print(person["name"])
person["age"] = 31
person["city"] = "Karachi"
print(person)
Output:
Ahmed
{'name': 'Ahmed', 'age': 31, 'city': 'Karachi'}
If I access a key that doesn’t exist using square brackets, Python raises a KeyError. To avoid this, I use .get():
print(person.get("country"))
print(person.get("country", "Unknown"))
Output:
None
Unknown
Common Dictionary Methods
keys(), values(), and items()
print(list(person.keys()))
print(list(person.values()))
print(list(person.items()))
Output:
['name', 'age', 'city']
[31, 'Ahmed', 'Karachi']
[('name', 'Ahmed'), ('age', 31), ('city', 'Karachi')]
These return special view objects, which are dynamic — if the dictionary changes afterward, the view reflects those changes automatically.
keys_view = person.keys()
person["country"] = "Pakistan"
print(keys_view)
Output:
dict_keys(['name', 'age', 'city', 'country'])
pop() and popitem()
age = person.pop("age")
print(age)
print(person)
last_pair = person.popitem()
print(last_pair)
print(person)
Output:
31
{'name': 'Ahmed', 'city': 'Karachi', 'country': 'Pakistan'}
('country', 'Pakistan')
{'name': 'Ahmed', 'city': 'Karachi'}
popitem() removes and returns the last inserted key-value pair (LIFO order), a guarantee that’s been in place since Python 3.7.
update()
person.update({"age": 32, "job": "Engineer"})
print(person)
Output:
{'name': 'Ahmed', 'city': 'Karachi', 'age': 32, 'job': 'Engineer'}
setdefault()
value = person.setdefault("hobby", "Reading")
print(value)
print(person)
Output:
Reading
{'name': 'Ahmed', 'city': 'Karachi', 'age': 32, 'job': 'Engineer', 'hobby': 'Reading'}
If the key already exists, setdefault() just returns the existing value without overwriting it — I use this a lot when building grouped data structures.
groups = {}
words = ["apple", "banana", "avocado", "blueberry", "cherry"]
for word in words:
first_letter = word[0]
groups.setdefault(first_letter, []).append(word)
print(groups)
Output:
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
Dictionary Comprehensions
squares = {n: n ** 2 for n in range(1, 6)}
print(squares)
filtered = {k: v for k, v in squares.items() if v > 10}
print(filtered)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{4: 16, 5: 25}
Internal Working: Dictionaries as Hash Tables
This is the part I find genuinely fascinating. CPython implements dictionaries as hash tables. When I insert a key-value pair, Python computes hash(key) and uses that hash value to determine where to store the entry in an internal array. When I look up a key, Python re-computes its hash and jumps almost directly to the right “bucket” rather than scanning every entry — this is why dictionary lookups are, on average, O(1), regardless of how many items the dictionary holds.
print(hash("name"))
print(hash(42))
The exact hash values vary between runs for strings (due to hash randomization for security reasons, introduced to prevent certain denial-of-service attacks), but the mechanism is consistent: equal objects always produce equal hashes within a single run.
Why Keys Must Be Hashable
Because dictionaries rely on hashing, keys must be hashable — meaning they need a __hash__ method and must be immutable in practice (or at least not change while used as a key). This is why lists can’t be dictionary keys, but tuples can:
d = {(1, 2): "point A"}
print(d)
try:
d2 = {[1, 2]: "invalid"}
except TypeError as e:
print("Error:", e)
Output:
{(1, 2): 'point A'}
Error: unhashable type: 'list'
Insertion Order Guarantee
Since Python 3.7, dictionaries officially guarantee that keys maintain their insertion order. Internally, CPython achieves this using a “compact dict” implementation, where a separate ordered array tracks insertion sequence, while a smaller hash table maps hash values to positions in that array. This design saved memory compared to earlier implementations while adding the ordering guarantee as a nice side effect — PEP 468 also confirms that keyword arguments preserve order in **kwargs, relying on this same underlying dict behavior.
Performance Characteristics
| Operation | Average Time Complexity |
|---|---|
| Get item | O(1) |
| Set item | O(1) |
| Delete item | O(1) |
Membership test (key in dict) | O(1) |
| Iteration | O(n) |
These are average complexities — in rare worst-case scenarios involving many hash collisions, operations can degrade to O(n), but Python’s hashing algorithm and collision resolution strategy make this extremely unlikely in normal use.
Merging Dictionaries
Python 3.9 introduced the | and |= operators for merging dictionaries, which I now use instead of update() in a lot of cases:
defaults = {"theme": "light", "language": "en"}
overrides = {"language": "ur"}
merged = defaults | overrides
print(merged)
Output:
{'theme': 'light', 'language': 'ur'}
Real-World and Automation Use Cases
- Counting occurrences, a classic pattern I use constantly:
text = "the quick brown fox jumps over the lazy dog the fox runs"
word_counts = {}
for word in text.split():
word_counts[word] = word_counts.get(word, 0) + 1
print(word_counts)
Output:
{'the': 3, 'quick': 1, 'brown': 1, 'fox': 2, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1, 'runs': 1}
- Caching/memoization, storing previously computed results keyed by input.
- Configuration management, storing application settings as key-value pairs.
- JSON data handling, since Python dictionaries map almost directly onto JSON objects when using the
jsonmodule. - Grouping and indexing records by a specific field, like grouping transactions by customer ID.
Common Mistakes and Debugging Tips
- Using square-bracket access on a possibly missing key. I use
.get()with a default value instead of risking aKeyError. - Mutating a dictionary while iterating over it. This raises a
RuntimeError: dictionary changed size during iteration.
d = {"a": 1, "b": 2, "c": 3}
try:
for key in d:
if d[key] == 2:
del d[key]
except RuntimeError as e:
print("Error:", e)
The fix is to iterate over a copy of the keys: for key in list(d.keys()):.
- Assuming dictionaries are sorted by key. They preserve insertion order, not sorted order — I use
sorted(d.items())if I actually need sorted output. - Using mutable objects as keys. Only immutable, hashable types (strings, numbers, tuples of immutables) work as dictionary keys.
Best Practices I Follow
- Use
.get()or.setdefault()instead of manually checkingif key in dictfollowed by direct access, when appropriate. - Use
collections.defaultdictfor grouping patterns instead of manually callingsetdefault()repeatedly, when it fits the use case.
from collections import defaultdict
groups = defaultdict(list)
for word in ["apple", "banana", "avocado"]:
groups[word[0]].append(word)
print(dict(groups))
- Use dictionary comprehensions for concise transformations.
- Prefer the
|merge operator (Python 3.9+) overupdate()when I want a new merged dictionary rather than in-place modification.
FAQs
Q: Are Python dictionaries ordered? Yes, since Python 3.7, insertion order is guaranteed and part of the language specification.
Q: Can dictionary keys be of different types within the same dictionary? Yes, as long as each individual key is hashable.
Q: What happens if I use a duplicate key in a dictionary literal? The last value assigned to that key wins; earlier duplicates are silently overwritten.
Q: How do dictionaries compare to lists for lookups? Dictionary lookups by key are O(1) on average; searching a list for a value is O(n).
Troubleshooting Tips
- If you get a
KeyError, use.get()with a default or checkif key in dictbefore accessing. - If you get
RuntimeError: dictionary changed size during iteration, iterate over a copy of the keys or items instead of the live dictionary. - If you get
TypeError: unhashable type, check whether you’re using a list or another dictionary as a key — switch to a tuple or another immutable type instead.
Summary
Understanding dictionaries as hash tables — not just as “key-value containers” — completely changed how I think about performance in my Python code. Whenever I need fast lookups, grouping, counting, or configuration storage, dictionaries are almost always my first choice, and knowing their internal behavior helps me avoid subtle bugs around ordering, hashability, and iteration.