exit
Author’s Note: As I write this series on Python programming, I’m learning right alongside you. Each article represents my own exploration of Python concepts, and I hope my discoveries and explanations help you on your own coding path. Let’s learn together!
Introduction
When you start programming in Python, you’re going to discover that organizing data is just as important as writing the code itself. While lists are great for storing sequences of items, sometimes you need a more flexible way to connect pieces of information. That’s where dictionaries come in.
Think of a dictionary like a real-world phone book (remember those?). You look up someone’s name (the key) to find their phone number (the value). Python dictionaries work the same way, they store pairs of related information that you can quickly access using meaningful labels instead of numeric positions.
What Are Dictionaries?
A dictionary in Python is a collection that stores data in key-value pairs. Each piece of data (value) is associated with a unique identifier (key). Here’s what makes dictionaries special:
- Mutable: You can change, add, or remove items after creation
- Unordered (before Python 3.7): Items had no specific order
- Ordered (Python 3.7+): Items maintain insertion order
- Fast lookups: Finding items by key is very quick
Simple Dictionary Example
# Creating a dictionary of student grades
= {
student_grades 'Alice': 85,
'Bob': 92,
'Charlie': 78
}
# Accessing a value
print(student_grades['Alice']) # Output: 85
85
Dictionary vs. List: When to Use Which?
Understanding when to use a dictionary versus a list is crucial for writing efficient Python code. Let’s compare them side by side:
Feature | Dictionary | List |
---|---|---|
Access Method | By key (any immutable type) | By index (integer) |
Order | Insertion order (Python 3.7+) | Always ordered |
Speed for Search | Very fast (constant time) | Slower (linear time) |
Use Case | Mapping relationships | Sequential data |
Example | {'name': 'Alice', 'age': 30} |
['Alice', 'Bob', 'Charlie'] |
Creating and Accessing Dictionaries
There are several ways to create dictionaries in Python:
Method 1: Using Curly Braces
# Empty dictionary
= {}
empty_dict
# Dictionary with initial values
= {
person 'name': 'Alice',
'age': 30,
'city': 'New York'
}
print(person)
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Method 2: Using dict() Constructor
# From keyword arguments
= dict(name='Alice', age=30, city='New York')
person
# From a list of tuples
= [('apple', 2), ('banana', 3), ('orange', 1)]
items = dict(items)
fruit_count
print(person)
{'name': 'Alice', 'age': 30, 'city': 'New York'}
print(fruit_count)
{'apple': 2, 'banana': 3, 'orange': 1}
Accessing Values
= {'name': 'Alice', 'age': 30, 'city': 'New York'}
person
# Direct access (may raise KeyError if key doesn't exist)
print(person['name']) # Output: Alice
Alice
# Safe access with get() method
print(person.get('phone', 'No phone')) # Output: No phone
No phone
Dictionary Methods: Your Toolkit
Python dictionaries come with several built-in methods that make working with them easier:
1. keys() - Get All Keys
The keys()
method returns a view of all dictionary keys:
= {'Alice': 85, 'Bob': 92, 'Charlie': 78}
student_grades print(list(student_grades.keys()))
['Alice', 'Bob', 'Charlie']
# Output: ['Alice', 'Bob', 'Charlie']
2. values() - Get All Values
The values()
method returns a view of all dictionary values:
print(list(student_grades.values()))
[85, 92, 78]
# Output: [85, 92, 78]
3. items() - Get Key-Value Pairs
The items()
method returns a view of all key-value pairs as tuples:
for name, grade in student_grades.items():
print(f"{name}: {grade}")
Alice: 85
Bob: 92
Charlie: 78
# Output:
# Alice: 85
# Bob: 92
# Charlie: 78
4. get() - Safe Value Access
The get()
method retrieves a value safely, returning a default if the key doesn’t exist:
# Without get() - may cause error
# grade = student_grades['David'] # KeyError!
# With get() - safe
= student_grades.get('David', 0)
grade print(grade) # Output: 0
0
5. setdefault() - Set If Missing
The setdefault()
method sets a value only if the key doesn’t already exist:
# Counting characters in a string
= {}
char_count = "hello"
message
for char in message:
0)
char_count.setdefault(char, += 1 char_count[char]
0
0
0
1
0
print(char_count) # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
Method Comparison Table
Method | Purpose | Returns | Example |
---|---|---|---|
keys() |
Get all keys | View object | dict.keys() |
values() |
Get all values | View object | dict.values() |
items() |
Get all pairs | View object | dict.items() |
get() |
Safe access | Value or default | dict.get('key', default) |
setdefault() |
Set if missing | Value | dict.setdefault('key', default) |
Ordered Dictionaries: A Python Evolution
The History
Before Python 3.7, dictionaries had no guaranteed order. This changed:
- Python 3.6: Dictionaries preserved insertion order in CPython (implementation detail)
- Python 3.7+: Order preservation became an official language feature
What This Means for You
# In Python 3.7+, order is preserved
= {}
colors 'red'] = '#FF0000'
colors['green'] = '#00FF00'
colors['blue'] = '#0000FF'
colors[
print(list(colors.keys()))
['red', 'green', 'blue']
# Always outputs: ['red', 'green', 'blue']
Using OrderedDict (Still Useful!)
While regular dictionaries now preserve order, OrderedDict
from the collections
module still has unique features:
from collections import OrderedDict
# OrderedDict remembers the order of first insertion
= OrderedDict()
od 'a'] = 1
od['b'] = 2
od['c'] = 3
od[
# Moving an item to the end
'a')
od.move_to_end(print(list(od.keys())) # Output: ['b', 'c', 'a']
['b', 'c', 'a']
Your Turn!
Let’s create a simple inventory system for a game using dictionaries:
Challenge: Create a program that tracks player inventory items and their quantities. The program should:
- Start with an initial inventory
- Add new items
- Update quantities
- Display the total count of all items
Try coding this yourself before looking at the solution!
Click here for Solution!
# Game inventory system
= {
inventory 'sword': 1,
'shield': 1,
'potion': 5,
'gold': 50
}
def add_item(inventory, item, quantity):
"""Add or update an item in inventory"""
0)
inventory.setdefault(item, += quantity
inventory[item]
def display_inventory(inventory):
"""Display all items and total count"""
print("=== Inventory ===")
= 0
total for item, count in inventory.items():
print(f"{item}: {count}")
+= count
total print(f"\nTotal items: {total}")
# Adding loot from a treasure chest
= {'gold': 25, 'potion': 3, 'arrow': 20}
treasure for item, quantity in treasure.items():
add_item(inventory, item, quantity)
display_inventory(inventory)
=== Inventory ===
sword: 1
shield: 1
potion: 8
gold: 75
arrow: 20
Total items: 105
Quick Takeaways
• Dictionaries store key-value pairs for fast lookups by meaningful names • Use dictionaries when you need to map relationships or find items by unique identifiers
• Use lists when you need ordered sequences accessed by position • The get() method prevents errors when accessing potentially missing keys • The setdefault() method simplifies counting and grouping operations • Python 3.7+ dictionaries maintain insertion order automatically • Dictionary searches are much faster than list searches for large datasets
Conclusion
Python dictionaries are powerful tools for organizing and accessing data efficiently. By understanding the difference between dictionaries and lists, mastering key methods like get()
and setdefault()
, and knowing when to use each data structure, you’ll write cleaner and more efficient Python code.
Remember, the best way to learn is by doing. Start incorporating dictionaries into your projects whenever you need to create associations between pieces of data. Whether you’re building a contact list, tracking game scores, or organizing any kind of related information, dictionaries will make your code more readable and performant.
Ready to practice? Try rewriting some of your list-based code using dictionaries where appropriate. You might be surprised by how much clearer your code becomes!
Frequently Asked Questions
Q1: Can dictionary keys be any type? Dictionary keys must be immutable (unchangeable) types like strings, numbers, or tuples. Lists and other dictionaries cannot be keys because they can be modified.
Q2: What happens if I try to access a non-existent key? Using square brackets dict['key']
raises a KeyError
. Use the get()
method to avoid this error and provide a default value instead.
Q3: Are Python dictionaries the same as hash tables? Yes! Python dictionaries are implemented as hash tables under the hood, which is why they provide such fast lookups.
Q4: How do I merge two dictionaries? In Python 3.9+, use the merge operator: merged = dict1 | dict2
. For earlier versions, use: merged = {**dict1, **dict2}
.
Q5: When should I use OrderedDict instead of a regular dict? Use OrderedDict
when you need its special methods like move_to_end()
or when you need to ensure compatibility with Python versions before 3.7.
Engage!
Did this article help you understand Python dictionaries better? I’d love to hear about your experiences and any creative ways you’re using dictionaries in your projects! Share your thoughts in the comments below or connect with me on social media.
If you found this helpful, please share it with other Python learners. Remember, we’re all learning together!
References
Python Tutorial: Data Structures
Official Python documentation covering dictionaries, lists, and other data structures with beginner-friendly examples.Python Documentation: Mapping Types - dict
Complete reference for dictionary methods, operations, and behavior in Python.What’s New In Python 3.7
Official release notes explaining dictionary ordering preservation and other Python 3.7 features.Real Python: Common Python Data Structures Guide
Comprehensive guide comparing dictionaries, lists, and other Python data structures with performance insights.
Happy Coding! 🚀
You can connect with me at any one of the below:
Telegram Channel here: https://t.me/steveondata
LinkedIn Network here: https://www.linkedin.com/in/spsanderson/
Mastadon Social here: https://mstdn.social/@stevensanderson
RStats Network here: https://rstats.me/@spsanderson
GitHub Network here: https://github.com/spsanderson
Bluesky Network here: https://bsky.app/profile/spsanderson.com
My Book: Extending Excel with Python and R here: https://packt.link/oTyZJ
You.com Referral Link: https://you.com/join/EHSLDTL6