Dictionaries are implemented as hash tables, giving average O(1) time for lookups, insertions, and deletions by key. Keys must be hashable, so ints, strings, and tuples work, but lists and dicts don't, while values can be anything. Since Python 3.7, dictionaries also guarantee that iterating over them yields entries in the order they were inserted.
1Understanding Dictionaries
Dictionaries are implemented as hash tables, giving average O(1) time for lookups, insertions, and deletions by key. Keys must be hashable, so ints, strings, and tuples work, but lists and dicts don't, while values can be anything. Since Python 3.7, dictionaries also guarantee that iterating over them yields entries in the order they were inserted.
Use dict.get(key, default) or dict.setdefault(key, default) instead of checking whether a key exists first — it avoids doing the same hash lookup twice.
person = {"name": "Alice", "age": 30}
print(person["name"])
print(person.get("email", "not provided"))2Practical Example
Here is a real-world application of Dictionaries showing how it is used in production Python code.
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts)3Best Practices
Follow these guidelines when working with Dictionaries:
1. Use dict.get(key, default) to avoid a KeyError instead of wrapping direct access in try/except
2. Use a dict comprehension instead of a for loop with manual key assignment when building a dictionary from an iterable
3. Use collections.defaultdict when every key should start with a sensible default value, instead of manually checking for existence
Tip: Use dict.get(key, default) or dict.setdefault(key, default) instead of checking whether a key exists first — it avoids doing the same hash lookup twice.
person = {"name": "Alice", "age": 30}
print(person["name"])
print(person.get("email", "not provided"))