๐๏ธ What is a Dictionary?
A dictionary is a collection of key-value pairs. Instead of accessing items by position (like lists), you access them by a unique key. It's the Python equivalent of a real dictionary where you look up a word and find its meaning.
In plain English: create a mapping from keys to values so you can retrieve data by name, not by position.
Dictionaries are mutable (you can change them), unordered in Python < 3.7, and ordered in Python 3.7+. Keys must be hashable (usually strings or numbers), and values can be anything.
๐ฏ Key Characteristics of Dictionaries
๐ฆ The Business Scenario
A Mumbai-based bank needs to store customer details: name, account balance, last login date, and branch location. Instead of five separate variables, one dictionary holds everything. When a customer logs in or makes a transaction, the system looks up their data by name โ a fast key-value lookup.
๐ป Step 1: Create and Access a Customer Profile
๐ Step 2: Use .get() to Avoid KeyError
Accessing a non-existent key with dict[key] raises KeyError. The .get() method is safer โ it returns a default value if the key doesn't exist.
๐ Step 3: Iterate with .keys(), .values(), .items()
Dictionaries have three key methods for iteration. Use .items() most often โ it gives you both key and value in one loop.
โก Step 4: Count Occurrences Using Dict + .get()
A real-world pattern: use a dictionary to count how many times each unique item appears. This is the foundation of word frequency, user activity, and transaction analysis.
๐ Also Used In
Dictionaries Are Everywhere
๐ค AI & Machine Learning Connection
Every machine learning model uses dictionaries internally. Token vocabularies map words to integers. Word embeddings store dense vectors by word. Config files are dictionaries. JSON data (the standard format for APIs) is a nested dictionary. When you train a model, its learned weights are stored and accessed as dictionaries. Dictionaries are the hidden backbone of modern AI systems.
๐ฏ Mini Challenge
Create a dictionary for a small shop's inventory: product names as keys (e.g., "apple", "banana", "orange") and quantity as values (e.g., 50, 30, 25). Write a loop to print each product and its stock. Then use .get() to check if "mango" is in stock (it isn't), and print a "Not available" message using a default value.
inventory = {"apple": 50, "banana": 30, "orange": 25}. Loop with for item, qty in inventory.items():. Then use inventory.get("mango", "Not available").
๐ค Interview Questions
dict[key] raises KeyError if the key doesn't exist. dict.get(key) returns None by default, or a custom default if you provide one: dict.get(key, "default"). Use .get() in production code when a key might be missing.dict.get(word, 0) + 1 to safely increment counts. Alternatively, use collections.Counter(words) which is a dict subclass optimized for counting. Never use a list and .count() for each word โ that's O(nยฒ). The dict approach is O(n).RuntimeError: dictionary changed size during iteration. Solution: iterate over a copy of keys: for key in list(dict.keys()):, or iterate over a snapshot. Modern Python 3.7+ is stricter about this. In old code, mutating during iteration could silently skip or double-process items. Always build a new dict if you need to filter during iteration.๐ง Quick Quiz
customer.get("email", "unknown") return if "email" is not in the dictionary?del dict[key] do if the key doesn't exist?๐ Quick Cheatsheet
| Operation | Syntax | Notes |
|---|---|---|
| Create | d = {"key": "value"} | Empty: d = {} |
| Access | d[key] | Raises KeyError if missing |
| Safe access | d.get(key, default) | Returns default if missing |
| Add/update | d[key] = value | Creates or overwrites |
| Delete | del d[key] | Raises KeyError if missing |
| Delete safe | d.pop(key, default) | Returns and removes, with default |
| Check key | "key" in d | True/False, O(1) |
| Get keys | d.keys() | Iterable of keys |
| Get values | d.values() | Iterable of values |
| Get pairs | d.items() | Iterable of (key, value) tuples |
| Length | len(d) | Number of key-value pairs |
| Clear | d.clear() | Remove all items |
โ ๏ธ Common Mistakes
dict[key] without checking if the key existsKeyError. Always use dict.get(key, default) when a key might be missing. In production, wrap risky lookups in try/except or use a safe default.TypeError: unhashable type. Use immutable types: strings, numbers, tuples. Convert lists to tuples if you need them as keys: dict[tuple(my_list)] = value.for key in dict: and then del dict[key] raises RuntimeError. Solution: iterate over a copy: for key in list(dict.keys()): or for key in list(dict):.d2 = d1 creates a reference, not a copy. Both variables point to the same dict. Modify d2 and d1 changes too. Use d2 = d1.copy() for a shallow copy or d2 = dict(d1).โฆ Key Takeaways
- Dictionaries store key-value pairs, not items by position like lists
- Keys must be hashable (usually strings or numbers), values can be anything
- Use
.get(key, default)to safely access values without KeyError - Use
.items()to loop through both keys and values cleanly - Dictionary lookup is O(1) โ much faster than searching a list
- Never mutate a dict while iterating over it โ iterate over a copy of keys instead
- Dictionaries are the backbone of configuration, JSON data, and ML embeddings
Master Data Structures & Build Real Projects
Join the Best AI Program: The AI-Era Analyst โ 5 months, fully online, with placement assistance. Week 1 is free.
Explore The AI-Era Analyst โ