Topic 26 of 58
Dictionary Basics
Overview
Dictionaries (dict) are Python's implementation of Hash Maps. They store data in Key-Value pairs. Like Sets, they use hash tables, meaning retrieving a value by its key is blazingly fast (O(1) time complexity). Since Python 3.7, dictionaries are formally guaranteed to maintain insertion order. They are the backbone of Python; in fact, behind the scenes, Python uses dictionaries to track variables, scopes, and object attributes.
Syntax
python
user = {
"username": "Alice",
"role": "Admin",
"age": 28
}
# Accessing Values
print(user["username"]) # "Alice" (Throws KeyError if missing)
# Safe Accessing with Fallbacks
print(user.get("salary")) # None (Safe fallback)
print(user.get("salary", 0)) # 0 (Custom fallback)
# Adding or Updating Values
user["location"] = "New York" # Adds new key
user["age"] = 29 # Overwrites existing keyCommon Pitfalls
- Using mutable objects (like lists or other dictionaries) as keys. Dictionary keys MUST be strictly immutable and hashable (strings, integers, tuples).
- Trusting bracket notation
user['key']when processing external API data. If the key is missing, your app will crash. Always use.get('key')for untrusted data.
Interview Questions
Q:
What types of objects are permitted to be used as dictionary keys?
A:
Only hashable (immutable) objects. Strings, integers, floats, and tuples are perfectly fine. Lists, sets, and dictionaries will raise a TypeError.
Real-World Example
Frequency counting (the most common pattern in coding assessments).
example
python
votes = ["Apples", "Bananas", "Apples", "Oranges", "Bananas", "Apples"]
tally = {}
for item in votes:
# If item doesn't exist, .get() returns 0. Then we add 1.
tally[item] = tally.get(item, 0) + 1
print(tally)
# {'Apples': 3, 'Bananas': 2, 'Oranges': 1}Check Your Knowledge
Test your understanding of Dictionary Basics with these quick questions.