Topic 49 of 64
Dictionary Key-
Overview
Dictionaries are Python's most powerful built-in data structure — O(1) average key lookup via hash tables. Understanding dict creation, valid key types, and basic operations is essential for virtually every real Python project.
Syntax
python
# Creation
person = {"name": "Alice", "age": 30}
empty = {}
built = dict(name="Alice", age=30)
# Access
person["name"] # "Alice"
person.get("email") # None (safe, no KeyError)
person.get("email", "") # "" (default value)
# Modification
person["age"] = 31 # update
person["city"] = "NYC" # add new key
del person["city"] # delete
# Check membership
"name" in person # TrueCommon Pitfalls
- dict[key] raises KeyError if key doesn't exist — use dict.get(key, default) for safe access.
- Dict keys must be hashable — lists and dicts cannot be keys, but tuples can.
- Interview tip: Since Python 3.7+, dicts maintain insertion order — this is now part of the language spec, not just an implementation detail.
Real-World Example
Frequency counter using a dictionary
example
python
def word_count(text: str) -> dict[str, int]:
counts: dict[str, int] = {}
for word in text.lower().split():
word = word.strip(".,!?")
counts[word] = counts.get(word, 0) + 1
return dict(sorted(counts.items(), key=lambda x: -x[1]))
result = word_count("the quick brown fox jumps over the lazy dog")
print(result) # {'the': 2, 'quick': 1, ...}