Historical Context & Motivation
Imagine you have a contacts list on your phone. You don't scroll through every single entry counting "contact #1, contact #2, contact #3" until you find someone. Instead, you search by name and instantly get their phone number. This idea — looking something up by a meaningful label rather than a position number — is one of the oldest and most powerful ideas in computer science. It's the core principle behind dictionaries in Python.
In earlier programming, data was stored almost exclusively in arrays and lists, which rely on numeric indexes. As programs grew more complex — managing user accounts, product catalogs, and configuration settings — developers needed a way to associate keys with values directly. The data structure that solved this problem has appeared under many names across decades of computing history.
So the central question dictionaries answer is: How can we store data so that we can find any piece of it almost instantly, using a meaningful name rather than remembering a position number? Python's dict is the answer, and it is one of the most-used data structures in real-world Python code.
Core Principles & Definitions
A dictionary in Python is a collection of key-value pairs. Each key acts as a unique label, and each value is the data associated with that label. You create a dictionary with curly braces {} and separate each key from its value with a colon. Before diving into code, let's establish the foundational ideas that make dictionaries work.
Key-Value Pairs
key: value inside curly braces.Unique Keys
Mutable Structure
Fast Lookup
Key Restrictions
Visual Explanation — Inside a Dictionary
The diagram below illustrates the structure of a Python dictionary that stores information about a student. On the left, you see the keys, and on the right, the values each key maps to. Arrows show which value belongs to which key. Notice that the keys are strings, but the values can be different types — a string, an integer, and a float.
In the diagram, notice three important things. First, each key is a string enclosed in quotes. Second, the values are of mixed types — a string, an integer, and a float — which is perfectly valid in Python. Third, the arrows go one way: you use a key to find its value, not the other way around. If you want to find which key has the value "Alice", you'd need to search through all the values, which is slower than a key lookup.
How It Works — Creating, Reading, and Updating
Creating a Dictionary
There are two main ways to create a dictionary. The most common is literal syntax — you write curly braces with key-value pairs separated by commas. You can also create an empty dictionary and add pairs later. Here are both approaches:
{} enclose the dictionary. Each key: value pair is separated by a comma. Keys are usually strings or numbers.Reading a Value (Key Lookup)
To read a value from a dictionary, you use bracket notation by placing the key inside square brackets after the dictionary name. This is called a key lookup. If the key doesn't exist, Python raises a KeyError. You can avoid this by using the .get() method, which returns None (or a default you specify) if the key is missing.
"key". Raises KeyError if the key is not found.Updating and Adding Values
Updating a value uses the exact same bracket notation as reading, but combined with an assignment operator. If the key already exists, its value is overwritten. If the key doesn't exist yet, a brand-new key-value pair is added to the dictionary. This dual behavior — update or insert — is one of the most convenient features of dictionaries.
"key" exists, the value is replaced. If it does not exist, a new pair is created.Common Dictionary Operations
Beyond creating, reading, and updating, Python dictionaries come with several built-in operations that make them even more powerful. The diagram below shows a dictionary going through a sequence of common operations — from creation, through lookups and updates, to deletion and membership checks.
"english" was deleted, "math" was updated, and "art" was added.| Operation | Syntax | What It Does |
|---|---|---|
| Create | d = {"a": 1, "b": 2} | Builds a new dictionary with initial key-value pairs |
| Read (bracket) | d["a"] | Returns the value for key "a"; raises KeyError if missing |
| Read (safe) | d.get("a", default) | Returns the value or a default if the key is missing |
| Update / Add | d["a"] = 99 | Changes the value for existing key or adds a new key-value pair |
| Delete | del d["a"] | Removes the key-value pair entirely from the dictionary |
| Membership | "a" in d | Returns True if the key exists, False otherwise |
| Length | len(d) | Returns the number of key-value pairs in the dictionary |
Worked Example — Building a Grade Tracker
Let's walk through a realistic scenario. You're building a small program to track quiz scores for a class. You need to create a dictionary of student scores, look up a specific student's score, update a score after a regrade, and add a new student who just joined.
quiz_scores with three students and their scores. Use string names as keys and integer scores as values.quiz_scores = {"Maya": 85, "Jordan": 92, "Sam": 78}"Jordan". Python searches the dictionary for this key and returns the associated value.print(quiz_scores["Jordan"]) # Output: 92.get() method with a default value of 0.print(quiz_scores.get("Alex", 0)) # Output: 0 (no crash)"Sam" already exists, the old value (78) is replaced.quiz_scores["Sam"] = 83 # Dict is now {"Maya": 85, "Jordan": 92, "Sam": 83}"Alex" is not yet a key, Python creates a brand-new key-value pair.quiz_scores["Alex"] = 91 # Dict: {"Maya": 85, "Jordan": 92, "Sam": 83, "Alex": 91}print(quiz_scores) # {"Maya": 85, "Jordan": 92, "Sam": 83, "Alex": 91}
print(len(quiz_scores)) # 4d["key"] (reading/updating a dictionary) with my_list[0] (accessing a list by index). Both use square brackets, but dictionaries use keys (like strings) while lists use integer positions. Mixing these up will cause a KeyError or TypeError.Dictionaries vs. Lists — When to Use Each
You already know how to use lists to store ordered collections of data. So when should you reach for a dictionary instead? The key difference is how you access elements. Lists are position-based (you access item #0, #1, #2), while dictionaries are key-based (you access items by name). Each has strengths and trade-offs.
| Feature | List | Dictionary |
|---|---|---|
| Access method | By integer index: lst[0] | By key: d["name"] |
| Order | Always ordered by position | Preserves insertion order (Python 3.7+) |
| Duplicates | Allows duplicate values | Keys must be unique; values can repeat |
| Lookup speed | Searching for a value is slow for large lists | Looking up by key is very fast, even for huge dictionaries |
| Best used for | Ordered sequences — scores, steps, items in a queue | Labeled data — user profiles, settings, word counts |
| Syntax | [10, 20, 30] | {"a": 10, "b": 20} |
Connection to Advanced Concepts
The dictionary basics you've learned here are the foundation for several powerful techniques you'll encounter as you advance in Python. Understanding key-value pairs now prepares you for working with more complex data structures, file formats, and even web development. Here's a preview of where dictionaries lead.
| What You Know Now | Where It Leads |
|---|---|
| Simple key-value pairs with strings and numbers | Nested dictionaries — values that are themselves dictionaries, creating multi-level data structures |
Manual creation with {} | Dictionary comprehensions — building dictionaries in a single expressive line, similar to list comprehensions |
Using .get() for safe access | defaultdict and Counter — specialized dictionary types from Python's collections module that handle missing keys automatically |
| Storing data in Python objects | JSON (JavaScript Object Notation) — the most popular data format for web APIs, which maps directly to Python dictionaries |
| Key lookup for single values | Databases and ORM models — real-world database records are essentially rows of key-value pairs, with column names as keys |
If you've ever used a web API (like getting weather data or game stats), the data you received was almost certainly structured as nested dictionaries. Mastering the basics of creating, reading, and updating dictionaries is the essential first step toward working with real-world data in Python.
Practice Problems
prices = {"apple": 1.20, "banana": 0.50, "cherry": 2.00}, write a single Python expression that retrieves the price of a banana. Then write a statement that changes the price of an apple to 1.50.inventory = {"pencils": 50, "erasers": 30}. Write code that: (a) adds a new item "notebooks" with a quantity of 20, (b) increases the pencil count by 10 (without hardcoding 60), and (c) safely checks for "pens" and prints its quantity or "Not in stock" if it's missing."the cat sat on the mat", write Python code that builds a dictionary where each key is a word and each value is the number of times it appears. Use a for loop, .split(), and the .get() method.data = {"id": 1, "name": "Laptop", "id": 2}
What value does data["id"] return? Based on this, write a rule for how Python handles duplicate keys when creating a dictionary, and suggest how your classmate should fix their code.Lesson Summary
A Python dictionary is a collection of key-value pairs enclosed in curly braces. You create a dictionary with {"key": value} syntax and read values using bracket notation (d["key"]) or the safer .get() method. You update existing values and add new pairs using the same d["key"] = value assignment syntax. Keys must be unique and immutable (strings, numbers, or tuples), while values can be any type.
Dictionaries differ from lists because they use meaningful keys rather than numeric positions, and their hashing mechanism makes lookups extremely fast regardless of size. Use "key" in d to check membership, del d["key"] to delete entries, and len(d) to count pairs. Mastering these basics opens the door to nested dictionaries, JSON data, and the many advanced dictionary tools in Python's standard library.