1. Introduction
A dictionary (dict) is Python's built-in mapping type that stores data as key-value pairs. Each key must be unique and hashable, and it maps to an associated value, allowing very fast lookups, insertions, and deletions by key.
Cricket analogy: A scorer's player-to-runs mapping is a dict—each player name (key) must be unique and maps to their score (value), enabling instant lookup of "how many runs did Kohli score" without scanning the whole innings.
Dictionaries are defined with curly braces {} containing key: value pairs separated by commas. They are widely used for representing structured data, counting occurrences, caching, and configuration settings.
Cricket analogy: A dict like {"Kohli": 82, "Rohit": 45} defined with curly braces is how a scorer tallies runs per batsman, and the same structure works for counting boundaries or caching last innings' totals for quick reference.
2. Syntax
# Creating dictionaries
empty_dict = {}
person = {"name": "Alice", "age": 30}
# Accessing and modifying values
name = person["name"]
person["age"] = 31
person["city"] = "NYC" # adds a new key
# Safe access
city = person.get("country", "Unknown")
# Common methods
keys = person.keys()
values = person.values()
items = person.items()
person.pop("city")
# Iterating
for k, v in person.items():
pass3. Explanation
Dictionary keys must be hashable — meaning immutable types like strings, numbers, and tuples (of hashable items) can be keys, but mutable types like lists and other dicts cannot. Values, on the other hand, can be of any type, including other dictionaries or lists.
Cricket analogy: A scorecard can't use a lineup (a mutable list of batsmen) as a dictionary key because it might change mid-match, but it can happily use a player's fixed jersey number as the key mapping to a nested dict of full stats as the value.
Since Python 3.7, dictionaries officially guarantee that they preserve insertion order — iterating over a dict yields keys in the order they were added, which is useful for predictable output and ordered processing.
Cricket analogy: Since a scorecard now guarantees deliveries are listed in the order they were bowled, a commentator can iterate ball-by-ball exactly as it happened, just as dicts since Python 3.7 preserve insertion order.
Using a mutable object like a list as a dictionary key raises TypeError: unhashable type: 'list'. If you need a composite key, use a tuple instead, e.g. cache[(x, y)] = result.
Accessing a missing key with person['country'] raises a KeyError. Prefer person.get('country', default) or if key in person: to avoid exceptions when a key might not exist.
4. Example
person = {}
person["name"] = "Alice"
person["age"] = 30
person["city"] = "NYC"
for key, value in person.items():
print(key, "->", value)
print("get missing:", person.get("country", "Unknown"))
try:
print(person["country"])
except KeyError as e:
print("KeyError:", e)
try:
bad = {[1, 2]: "value"}
except TypeError as e:
print("TypeError:", e)5. Output
name -> Alice
age -> 30
city -> NYC
get missing: Unknown
KeyError: 'country'
TypeError: unhashable type: 'list'6. Key Takeaways
- Dictionaries store unique, hashable keys mapped to values of any type.
- Since Python 3.7, dicts preserve insertion order when iterated.
- Accessing a missing key with
[]raises KeyError; use.get()for a safe default. - Lists and other dicts cannot be used as keys because they are unhashable; use tuples instead.
.keys(),.values(), and.items()return view objects that reflect live changes to the dict.dict.pop(key)removes a key and returns its value, similar tolist.pop()for lists.
Practice what you learned
1. What happens when you access a dictionary key that doesn't exist using `d[key]`?
2. Which of these can be used as a dictionary key?
3. Since which Python version do dictionaries officially guarantee insertion order?
4. What does `person.get('country', 'Unknown')` return if 'country' is not a key in person?
5. What does `d.items()` return?
6. Why does `{[1,2]: 'a'}` raise a TypeError?
Was this page helpful?
You May Also Like
Lists in Python
A mutable, ordered sequence type in Python used to store collections of items, with a deep dive into mutation, aliasing, and common list operations.
Sets in Python
An unordered collection of unique, hashable elements in Python, covering set creation, operations, and the no-order/no-duplicates gotcha.
Tuples in Python
An immutable, ordered sequence type in Python, covering tuple syntax, the nested-mutable-element trap, tuple packing/unpacking, and use cases.
Working with JSON in Python
Learn how to convert Python objects to and from JSON using the json module, including dumps/loads for strings and dump/load for files.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics