mapping
In Python, a mapping is a data structure that associates keys with values. The most common example of a mapping in Python is the built-in dict
data type, which allows you to store and retrieve data by using unique keys.
Mappings are a powerful tool when you need to efficiently look up data based on a unique identifier. In Python, the dictionary is implemented as a hash table, which provides efficient lookups, insertions, and deletions in constant time, O(1).
Example
Here’s an example of how to create and use a dictionary:
>>> ages = {
... "Alice": 28,
... "Bob": 34,
... "Charlie": 22
... }
>>> ages["Alice"]
28
>>> ages["David"] = 30
>>> ages
{
"Alice": 28,
"Bob": 34,
"Charlie": 22,
"David": 30
}
>>> ages["Alice"] = 29
>>> ages
{
"Alice": 29,
"Bob": 34,
"Charlie": 22,
"David": 30
}
In this example, you use a Python dictionary to store and manipulate key-value pairs. You can access values by their keys, add new pairs, or update existing values. Dictionaries are pretty efficient for such operations.
Related Resources
Tutorial
Dictionaries in Python
In this tutorial, you'll learn how to work with Python dictionaries to help you process data more efficiently. You'll learn how to create dictionaries, access their keys and values, update dictionaries, and more.
For additional information on related topics, take a look at the following resources:
- Build a Hash Table in Python With TDD (Tutorial)
- Custom Python Dictionaries: Inheriting From dict vs UserDict (Tutorial)
- Python Dictionary Comprehensions: How and When to Use Them (Tutorial)
- Python's Counter: The Pythonic Way to Count Objects (Tutorial)
- Using the Python defaultdict Type for Handling Missing Keys (Tutorial)
- OrderedDict vs dict in Python: The Right Tool for the Job (Tutorial)
- Using Dictionaries in Python (Course)
- Python Dictionaries (Quiz)
- Dictionaries in Python (Quiz)
- Building Dictionary Comprehensions in Python (Course)
- Python Dictionary Comprehensions: How and When to Use Them (Quiz)
- Counting With Python's Counter (Course)
- Handling Missing Keys With the Python defaultdict Type (Course)
- Using OrderedDict in Python (Course)
By Leodanis Pozo Ramos • Updated April 23, 2025