Dictionaries
Store and access data using key-value pairs for fast and organized data management.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
1. What Are Dictionaries?
A dictionary stores data in key-value pairs . Instead of accessing items by position (like lists), you access them by a unique key name.
Key Characteristics
- Key-value pairs — Each item has a name (key) and data (value)
- Fast lookups — Access any value instantly by its key
- Unique keys — Each key can only appear once
- Mutable — You can add, change, or remove items
- Ordered — Maintains insertion order (Python 3.7+)
2. Lists vs Dictionaries
Feature
List
Dictionary
Access by
Index (0, 1, 2...)
Key name
Syntax
[item1, item2]
Best for
Ordered collections
Named/labeled data
Example use
List of names
User profile info
3. Creating Dictionaries
Method
Example
Description
Empty dictionary
my_dict = {}
Start with nothing
With data
Key-value pairs
Using dict()
dict(name="Alice")
Constructor function
4. Accessing Values
There are two ways to access dictionary values:
Syntax
If Key Missing
Square brackets
dict["key"]
KeyError (crashes)
.get() method
dict.get("key")
Returns None (safe)
.get() with default
dict.get("key", "default")
Returns your default
5. Adding and Changing Items
Dictionaries are mutable — you can add new key-value pairs or update existing ones using the same syntax:
6. Removing Items
What It Does
del dict["key"]
Delete a specific key
del person["age"]
.pop("key")
Remove and return the value
age = person.pop("age")
.popitem()
Remove last inserted item
last = person.popitem()
.clear()
Remove all items
person.clear()
7. Checking if a Key Exists
Use in to check if a key exists before accessing it:
8. Looping Through Dictionaries
Loop Type
What You Get
Keys only
Each key
for key in dict:
Values only
Each value
for val in dict.values():
Both
Key and value
for key, val in dict.items():
9. Useful Dictionary Methods
What It Returns
.keys()
All keys
person.keys()
.values()
All values
person.values()
.items()
All key-value pairs
person.items()
.get(key)
Value or None
person.get("name")
.update(dict2)
Merges dict2 into dict
.copy()
A copy of the dict
new = person.copy()
len(dict)
Number of pairs
len(person)
10. Nested Dictionaries
Dictionaries can contain other dictionaries (or lists) as values. This is useful for organizing complex data.
11. Dictionary Comprehension (Advanced)
Like list comprehension, you can create dictionaries in one line:
12. Common Mistakes to Avoid
Mistake
Problem
Solution
Accessing missing key
dict["missing"]
Use .get() or check with in
Using list as key
Keys must be immutable (str, int, tuple)
Using square brackets
["key", "value"]
Use curly braces
Forgetting the colon
Use
Duplicate keys
Each key must be unique (last value wins)
13. Practical Examples
Example 1: User Profile
Example 2: Word Counter
Example 3: Simple Contact Book
Summary: Quick Reference
Operation
Create
Access (unsafe)
person["name"]
Access (safe)
Add/Change
dict["key"] = val
person["age"] = 25
Remove
Check exists
"key" in dict
"name" in person
Loop
for k, v in dict.items():
for k, v in person.items():
Length
Lesson 8 done — you can now model real-world data in Python!
Dictionaries are how Python stores structured data — user profiles, API responses, config settings. You know how to create, access, update, loop, and nest them safely.
🚀 Up next: File Handling — learn to save data permanently so it survives after your program closes.
Practice quiz
How does a dictionary store data?
- By index position
- In key-value pairs
- As a sorted set
- As a fixed tuple
Answer: In key-value pairs. Dictionaries store data as key-value pairs, accessed by key name.
Which brackets create a dictionary?
Dictionaries use curly braces, e.g. {"name": "Alice"}.
What happens when you access a missing key with dict['missing']?
- Returns None
- Returns 0
- Raises a KeyError
- Adds the key
Answer: Raises a KeyError. Square-bracket access on a missing key raises a KeyError.
What does person.get('email', 'N/A') return if 'email' is missing?
- None
- 'N/A'
- KeyError
- Empty string
Answer: 'N/A'. .get() returns the supplied default ('N/A') when the key is absent.
How do you add a new key 'age' with value 25 to dict person?
- person.add('age', 25)
- age
Answer: age. Assigning to a new key, person['age'] = 25, adds the pair.
Which loop gives you both keys and values?
- for k in dict:
- for v in dict.values():
- for k, v in dict.items():
- for i in dict.keys():
Answer: for k, v in dict.items():. .items() yields (key, value) pairs you can unpack in the loop.
Can a list be used as a dictionary key?
- Yes, always
- No, keys must be immutable
- Only if it's empty
- Only with .get()
Answer: No, keys must be immutable. Keys must be immutable (str, int, tuple); a list raises a TypeError.
What does {x: x**2 for x in range(1, 6)} create?
- {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
- {1, 4, 9, 16, 25}
Answer: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}. The dict comprehension maps each x (1-5) to its square.
If a dictionary literal has a duplicate key {'a': 1, 'a': 2}, what is the value of 'a'?
- 1
- 2
- Error
Answer: 2. Keys are unique; the last value wins, so 'a' is 2.
What does len() return for {'name': 'Alice', 'age': 25, 'city': 'London'}?
- 2
- 3
- 6
- 1
Answer: 3. len() counts the number of key-value pairs: 3.
Continue this course
- Previous: Lists
- Next: File Handling