๐Ÿ—‚๏ธ 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.

my_dict = { key : value, ... }

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

Key-Value
{"name": "Priya"}
Each value is paired with a unique key.
Fast Lookup
dict[key] โ†’ O(1)
Find values instantly by key, not by scanning.
Hashable Keys
str, int, tuple
Keys can't be lists or dicts โ€” must be immutable.
Mutable
Add/edit/delete
Change dict after creation without rebuilding.
Flexible Values
int, str, list, dict
Values can be any data type, including nested dicts.
Ordered
Python 3.7+
Keys maintain insertion order (a language guarantee).

๐Ÿฆ The Business Scenario

๐Ÿฆ
Banking ยท SouthBank India
Customer Profile Dictionary

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.

1
Customer record
4
Key-value pairs
<1ms
Lookup time

๐Ÿ’ป Step 1: Create and Access a Customer Profile

customer_profile.py โ–ถ Run to see output below
# Output Customer: Priya Sharma Balance: โ‚น177,500.00 Last login: 2024-04-12 Branch: Mumbai Downtown Account type: Savings Updated balance: โ‚น189,750.50

๐Ÿ”‘ 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.

safe_access.py โ–ถ Handling missing data
# Output Phone key not found Phone: None Phone: Not provided No active loan

๐Ÿ” 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.

dict_methods.py โ–ถ Common dict operations
# Output === Using .keys() === +254712345678 +254798765432 +254701234567 +254799999999 === Using .values() === 15 transactions 8 transactions 23 transactions 5 transactions === Using .items() (best for both key & value) === +254712345678: 15 txns +254798765432: 8 txns +254701234567: 23 txns +254799999999: 5 txns User found: 15 transactions After deletion, 3 users remain

โšก 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.

transaction_counts.py โ–ถ Frequency counting (M-Pesa use case)
# Output === Transaction Counts by Recipient === +254712345678: 3 transactions +254798765432: 2 transactions +254701234567: 1 transactions Most active recipient: +254712345678

๐ŸŒ Also Used In

Dictionaries Are Everywhere

๐Ÿ“ฑ
subscriber_profiles = {phone: {"plan": "4G", "balance": 450}}
Telecom โ€” store subscriber data keyed by phone number
๐Ÿฅ
patient_records = {patient_id: {"name": "...", "blood_type": "..."}}
Healthcare โ€” fast patient lookup by ID, not by scanning lists
๐Ÿ“Š
word_freq = {"the": 4521, "a": 2103, "is": 1890}
NLP & Text Analysis โ€” count word frequencies for models
๐Ÿค–
embeddings = {"cat": [0.2, 0.8, ...], "dog": [0.3, 0.7, ...]}
AI & ML โ€” store word embeddings, token mappings, config params

๐Ÿค– 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.

transformers word2vec json config embeddings

๐ŸŽฏ Mini Challenge

Build a Simple Inventory System

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.

Start with 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.
Yes. In Python 3.7+, dictionaries maintain insertion order as a language guarantee. In Python 3.6 (CPython), it was an implementation detail. Before 3.6, order was not guaranteed. Always assume order is preserved in modern Python โ€” this makes dictionaries more predictable and useful for serialization (e.g., to JSON).
Dictionaries use a hash table internally. When you look up a key, Python hashes it to find its storage location in O(1) time. Lists and dicts are mutable โ€” their hash value would change if modified, breaking the lookup guarantee. Immutable types (str, int, tuple) are hashable and safe as keys. This is a performance and correctness trade-off.
Use a dictionary: loop through words and use 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).
Bad idea. Adding or deleting keys while iterating raises 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

Question 1 of 5
What does customer.get("email", "unknown") return if "email" is not in the dictionary?
Question 2 of 5
Which of the following can be a dictionary key?
Question 3 of 5
How do you loop through both keys and values in a dictionary?
Question 4 of 5
What is the time complexity of looking up a key in a dictionary?
Question 5 of 5
What does del dict[key] do if the key doesn't exist?
0
/5

๐Ÿ“‹ Quick Cheatsheet

OperationSyntaxNotes
Created = {"key": "value"}Empty: d = {}
Accessd[key]Raises KeyError if missing
Safe accessd.get(key, default)Returns default if missing
Add/updated[key] = valueCreates or overwrites
Deletedel d[key]Raises KeyError if missing
Delete safed.pop(key, default)Returns and removes, with default
Check key"key" in dTrue/False, O(1)
Get keysd.keys()Iterable of keys
Get valuesd.values()Iterable of values
Get pairsd.items()Iterable of (key, value) tuples
Lengthlen(d)Number of key-value pairs
Cleard.clear()Remove all items

โš ๏ธ Common Mistakes

Using dict[key] without checking if the key exists
Raises KeyError. 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.
Trying to use a list or dict as a key
Lists and dicts are mutable and unhashable. You'll get TypeError: unhashable type. Use immutable types: strings, numbers, tuples. Convert lists to tuples if you need them as keys: dict[tuple(my_list)] = value.
Modifying a dictionary while iterating over it
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):.
Confusing dict assignment with copying
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
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

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 โ†’