- What is a dictionary — definition and characteristics
- Creating dictionaries — syntax and different ways
- Key-value pairs — understanding keys and values
- Dictionary vs List — key differences and when to use each
- Use cases — practical applications of dictionaries
Introduction to Dictionaries
A dictionary is an unordered, mutable collection of key-value pairs in Python. Dictionaries are defined using curly braces {} and store data in a structure that maps unique keys to values.
The key characteristics of dictionaries are:
- Key-value pairs — each element consists of a key and a value
- Unique keys — keys must be unique within a dictionary
- Mutable — can add, remove, and modify key-value pairs
- Unordered — insertion order is not guaranteed (Python 3.7+ preserves insertion order)
- Hashable keys — keys must be immutable (strings, numbers, tuples)
💡 Key concept: Dictionaries are ideal for storing data that needs to be accessed by a unique identifier (key), rather than by position (index).
Creating Dictionaries
Dictionary Creation Methods
Dictionaries can be created using curly braces {}, the dict() constructor, or using the dict.fromkeys() method.
# Using curly braces (most common)
person = {"name": "Alice", "age": 25, "city": "NYC"}
print(person) # {'name': 'Alice', 'age': 25, 'city': 'NYC'}
# Using the dict() constructor
person = dict(name="Bob", age=30, city="LA")
print(person) # {'name': 'Bob', 'age': 30, 'city': 'LA'}
# Empty dictionary
empty = {}
print(empty) # {}
# From a list of tuples
items = [("name", "Charlie"), ("age", 35)]
person = dict(items)
print(person) # {'name': 'Charlie', 'age': 35}
# Using dict.fromkeys() (creates dictionary with default values)
keys = ["name", "age", "city"]
person = dict.fromkeys(keys)
print(person) # {'name': None, 'age': None, 'city': None}
# With a default value
person = dict.fromkeys(keys, "unknown")
print(person) # {'name': 'unknown', 'age': 'unknown', 'city': 'unknown'}
Important notes:
- Use
{}for non-empty dictionaries with key-value pairs - Use
dict()for creating from other structures - Keys must be hashable (immutable types)
- Values can be any data type
Quick Check: What is the correct way to create an empty dictionary? (Answer: {} — set() creates an empty set)
Key Characteristics
Understanding Dictionary Properties
Dictionaries have several unique properties that distinguish them from other data structures.
# 1. Key-value pairs
person = {"name": "Alice", "age": 25}
print(person["name"]) # Alice
print(person["age"]) # 25
# 2. Unique keys (duplicate keys overwrite)
person = {"name": "Alice", "name": "Bob"}
print(person) # {'name': 'Bob'} — last value wins
# 3. Mutable (can be modified)
person = {"name": "Alice", "age": 25}
person["age"] = 26 # Update
person["city"] = "NYC" # Add new
print(person) # {'name': 'Alice', 'age': 26, 'city': 'NYC'}
# 4. Unordered (Python 3.6+ preserves insertion order)
person = {"name": "Alice", "age": 25, "city": "NYC"}
print(person) # Insertion order is maintained in Python 3.7+
# 5. Keys must be hashable (immutable)
valid_dict = {1: "one", "two": 2, (1, 2): "tuple"}
# invalid_dict = {[1, 2]: "list"} # TypeError: unhashable type: 'list'
Key properties:
- Key-value pairs — each key maps to a value
- Unique keys — keys must be unique
- Mutable — can add, remove, and update
- Hashable keys — keys must be immutable
- Insertion order — Python 3.7+ preserves order
Quick Check: Can a list be used as a dictionary key? (Answer: No — lists are mutable and unhashable)
Dictionary vs List
Key Differences
Understanding the differences between dictionaries and lists helps you choose the right data structure for your needs.
# Comparison of dictionary and list
# 1. Access method
my_list = [10, 20, 30, 40, 50]
my_dict = {"a": 10, "b": 20, "c": 30}
print(my_list[0]) # 10 — access by index
print(my_dict["a"]) # 10 — access by key
# 2. Performance (lookup speed)
import time
large_list = list(range(1000000))
large_dict = {i: i for i in range(1000000)}
start = time.time()
999999 in large_list
print(f"List membership: {time.time() - start:.6f}s")
start = time.time()
999999 in large_dict
print(f"Dict membership: {time.time() - start:.6f}s")
# 3. Ordering
my_list = [1, 2, 3] # Order is guaranteed
my_dict = {"a": 1, "b": 2, "c": 3} # Order preserved in Python 3.7+
# 4. Mutability
my_list = [1, 2, 3]
my_dict = {"a": 1, "b": 2}
my_list[0] = 10 # Works
my_dict["a"] = 10 # Works
When to use each:
- Use dictionaries when:
- You need to access elements by a unique key
- Fast lookup by key is important
- You have key-value pairs data
- Order doesn't matter (or Python 3.7+ order is sufficient)
- Use lists when:
- Order matters
- You need index-based access
- You have a sequence of items
- You need to perform operations on all items
Practical Use Cases
Real-World Applications
Dictionaries are used in many practical scenarios in Python programming.
# 1. Storing user data
user = {
"id": 1001,
"name": "Alice Smith",
"email": "alice@example.com",
"active": True
}
print(f"User: {user['name']}")
# 2. Configuration settings
config = {
"host": "localhost",
"port": 8080,
"debug": True,
"timeout": 30
}
print(f"Server running on {config['host']}:{config['port']}")
# 3. Counting occurrences
text = "the cat in the hat with the cat and the hat"
words = text.split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count)
# 4. Mapping IDs to objects
employees = {
101: {"name": "Alice", "department": "Engineering"},
102: {"name": "Bob", "department": "Marketing"},
103: {"name": "Charlie", "department": "Sales"}
}
print(employees[101]["name"])
# 5. Lookup tables
color_codes = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF"
}
print(color_codes["green"]) # #00FF00
Common Mistakes
Pitfalls and Solutions
Mistake 1: Using a Mutable Key
# WRONG — raises TypeError
my_dict = {}
# my_dict[[1, 2]] = "value" # TypeError: unhashable type: 'list'
# CORRECT — use immutable types
my_dict[(1, 2)] = "value" # Tuple is hashable
Mistake 2: Accessing a Non-Existent Key
# WRONG — raises KeyError
person = {"name": "Alice", "age": 25}
# print(person["city"]) # KeyError: 'city'
# CORRECT — use get() method
city = person.get("city", "Unknown")
print(city) # Unknown
Mistake 3: Assuming Dictionary Order
# WRONG — order is not guaranteed in older Python versions
my_dict = {"a": 1, "b": 2, "c": 3}
# Order is preserved in Python 3.7+ but not guaranteed in earlier versions
# CORRECT — use OrderedDict if order matters
from collections import OrderedDict
ordered = OrderedDict([("a", 1), ("b", 2), ("c", 3)])
Quick Check: What is the most common mistake with dictionaries? (Answer: Using mutable objects as keys — raises TypeError)
Interactive Editor
Experiment with dictionaries in the interactive editor below. Modify the code and observe the results in real time.
DICTIONARY PRACTICE
========================================
1. CREATING DICTIONARIES
Person: {'name': 'Alice', 'age': 25, 'city': 'NYC'}
2. ACCESSING VALUES
Name: Alice
Age: 25
3. ADDING AND UPDATING
Updated: {'name': 'Alice', 'age': 26, 'city': 'NYC', 'email': 'alice@example.com'}
4. DICTIONARY OPERATIONS
Keys: ['name', 'age', 'city', 'email']
Values: ['Alice', 26, 'NYC', 'alice@example.com']
Items: [('name', 'Alice'), ('age', 26), ('city', 'NYC'), ('email', 'alice@example.com')]
5. WORD COUNT EXAMPLE
Word count: {'the': 3, 'cat': 2, 'in': 1, 'hat': 2, 'with': 1, 'and': 1}
Dictionary practice complete!
Certificate of Completion
You have completed the Python Dictionary tutorial. You now understand dictionary creation, key-value pairs, characteristics, and the key differences between dictionaries and lists.
Quick Quiz — Test Your Knowledge
Let's see what you've learned about dictionaries:
Frequently Asked Questions
What is a dictionary in Python?
{} and store data that can be accessed by a unique key.
What is the difference between a dictionary and a list?
Can a dictionary have duplicate keys?
What types can be used as dictionary keys?
Are dictionaries ordered in Python?
OrderedDict.
How do I safely access a dictionary value without raising an error?
get() method: dict.get(key, default_value). This returns the value if the key exists, otherwise returns the default value (or None).
Where to Go From Here
After mastering dictionaries, consider exploring these related topics:
Access Dictionary Items
Learn how to access, add, and update dictionary items.
Learn More →Dictionary Methods
Explore built-in dictionary methods and operations.
Learn More →List vs Dictionary
Detailed comparison of lists and dictionaries.
Learn More →