Definition
How does a phone book find a number instantly, without reading every page?
A dictionary stores key-value pairs: each unique key maps to a value, such as {"Riya": 91}. Values are looked up by key rather than by position, very quickly. Dictionaries are changeable, keep insertion order, and their values can themselves be lists or dictionaries.
In simple words
A dictionary is like a real dictionary: look up a word (the key) and get its meaning (the value). marks["Riya"] gives Riya's marks. marks["Kabir"] = 78 adds or updates Kabir. To count words, use each word as a key and its count as the value.
Overview
- A dictionary stores key-value pairs: {"Delhi": 32, "Shimla": 18}.
- Values are looked up by key, not by position, in roughly constant time thanks to hashing.
- Keys must be unique and immutable (strings, numbers, tuples); values can be anything.
- Since Python 3.7, dictionaries keep items in the order they were inserted.
- d[key] raises KeyError for a missing key; d.get(key, default) returns a default instead.
- keys(), values() and items() let you loop over a dictionary's parts.
Why it matters
Dictionaries are everywhere in AI code: word counts, settings for a model, a row of data with named columns, and the JSON that web APIs and LLMs send back.
Key terms
- Dictionary
- A collection of key-value pairs, written {key: value}.
- Key
- The unique, hashable label used to look up a value.
- Value
- The data stored under a key; it can be anything, including a list or dictionary.
- get()
- Looks up a key and returns a default instead of raising an error if it is missing.
- items()
- Gives the key-value pairs, for looping over both at once.
- JSON
- A text format for data that looks almost exactly like Python dictionaries and lists.
Types
Dictionaries come in several shapes and specialised versions. These are the types used most in data and AI work.
1. Plain dictionary (lookup table)
A flat mapping from keys to single values.
- How it works: Create it with braces or dict(); read, add and update with d[key]; delete with del or pop().
- Example: pin_codes = {"Delhi": "110001", "Mumbai": "400001"}.
- When to use it: Use it whenever you look things up by a name or code: prices, translations, settings.
2. Nested dictionary
A dictionary whose values are themselves dictionaries or lists.
- How it works: Each level is reached with another key: data["Asha"]["maths"]; this mirrors JSON data from web APIs.
- Example: students = {"Asha": {"maths": 91, "science": 84}}.
- When to use it: Use it for records with several fields and for JSON from APIs and configuration files.
3. Grouping dictionary (dict of lists)
A dictionary whose values are lists collecting all items in each group.
- How it works: Loop over the data and append each item to the list for its key, creating the list when a key first appears.
- Example: by_city = {"Pune": ["Asha", "Ravi"], "Delhi": ["Meera"]}.
- When to use it: Use it to group records by category before summarising, like a hand-made groupby.
4. defaultdict
A dictionary from the collections module that creates a default value for missing keys.
- How it works: defaultdict(list) makes an empty list and defaultdict(int) makes 0 the first time a key is used, so no KeyError occurs.
- Example: groups = defaultdict(list); groups[city].append(name).
- When to use it: Use it for grouping and counting without writing "if key not in d" checks.
5. Counter
A dictionary subclass from collections that counts how often each item appears.
- How it works: Counter(iterable) counts items; most_common(n) returns the n most frequent; counters can be added and subtracted.
- Example: Counter("banana") gives {'a': 3, 'n': 2, 'b': 1}; word frequencies in a document.
- When to use it: Use it for frequency counts: votes, words, items sold, bigrams in language models.
Explained in detail
Looking things up by name
Lists find items by position; dictionaries find them by key. marks = {"Riya": 91, "Arjun": 78} lets you write marks["Riya"] instead of remembering that Riya is item 0. Like sets, dictionaries use a hash table, so looking up a key takes about the same time whether the dictionary has ten entries or ten million. That speed is why dictionaries sit underneath so much of Python itself, and why they are used for counting, caching, configuration and any kind of mapping from one thing to another.
Everyday operations
| Task | How |
|---|---|
| Add or update | marks["Sara"] = 85 |
| Safe lookup | marks.get("Ravi", 0) returns 0 if Ravi is missing |
| Check for a key | "Riya" in marks |
| Remove | marks.pop("Arjun") or del marks["Arjun"] |
| Loop over pairs | for name, mark in marks.items(): |
| Merge | combined = marks | extra (Python 3.9+) |
The counting pattern
One of the most useful dictionary patterns counts how often things appear. Start with an empty dictionary; for each word, do counts[word] = counts.get(word, 0) + 1. After the loop, counts holds every word and its frequency, which is exactly the word-count step at the heart of bag-of-words models in NLP. Python's collections module offers Counter, which does this in one line, Counter(words), and adds handy extras such as most_common(3).
Nested data and JSON
Values can be lists or other dictionaries, so one dictionary can describe a whole record: {"name": "Riya", "marks": {"maths": 91, "science": 88}, "clubs": ["robotics", "music"]}. You reach inside step by step: student["marks"]["maths"] is 91. This shape is the same as JSON, the format most web services and AI APIs use to send data. The json module converts between them with json.loads() and json.dumps(), so understanding dictionaries means you already understand most of the data you will receive from an AI model's API.
- Keys must be immutable: strings, numbers and tuples work; lists do not.
- Since Python 3.7, dictionaries remember insertion order.
- Assigning to an existing key replaces its value; keys are never duplicated.
A related tool, collections.defaultdict, creates a missing key automatically with a starting value, so defaultdict(list) lets you write groups[subject].append(name) without first checking whether the subject exists. This grouping pattern, collecting items under a shared key, is exactly what pandas later does with groupby() on whole tables.
How it works
| Operation | Example |
|---|---|
| Look up | marks["Riya"] |
| Look up safely, with a default | marks.get("Zara", 0) |
| Add or update | marks["Kabir"] = 78 |
| Check a key | "Riya" in marks |
| Loop over pairs | for name, m in marks.items(): |
| Remove | del marks["Riya"] |
In code
Counting words with a dictionary, then a nested dictionary for a student record.
text = "ai helps people and people build ai and ai learns"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
most = max(counts, key=counts.get)
print("Most common word:", most, "appears", counts[most], "times")
student = {"name": "Meera", "marks": {"maths": 91, "science": 88}}
print(student["name"], "scored", student["marks"]["maths"], "in maths")
for subject, score in student["marks"].items():
print(" ", subject, score)Output
{'ai': 3, 'helps': 1, 'people': 2, 'and': 2, 'build': 1, 'learns': 1}
Most common word: ai appears 3 times
Meera scored 91 in maths
maths 91
science 88Try it yourself
Predict the lookup
For ages = {"Aarav": 14, "Sana": 16}, what does each give?
- ages["Sana"]
- ages.get("Zoya", 0)
- "Aarav" in ages
- len(ages)
- ages["Zoya"]
Common mistakes
- Using [ ] for a key that may be missing.
- Using a list as a key. Keys must be unchangeable, such as strings, numbers or tuples.
- Expecting two equal keys. A new value for an existing key replaces the old one.
Check yourself
Summary
- Dictionaries map unique keys to values for fast lookup.
- Use .get() for keys that may be missing.
- Loop with .items(); nest dictionaries for structured records.
Finished reading?
Sources: Python docs: Data Structures