dict
The built-in dict data type, short for dictionary, represents a collection of key-value pairs, where keys are unique and hashable, and are used to access corresponding values. Mutable objects such as lists and dictionaries can’t be used as keys. Dictionaries are mutable, meaning they can be dynamically modified and expanded. They also preserve insertion order, so iterating a dictionary yields its keys in the order they were first added.
Here’s a basic example of creating a dictionary and accessing one of its values:
>>> teams = {
... "Colorado": "Rockies",
... "Boston": "Red Sox",
... "Minnesota": "Twins",
... "Milwaukee": "Brewers",
... "Seattle": "Mariners",
... }
>>> teams["Minnesota"]
'Twins'
dict Constructors
dict(**kwargs)
dict(mapping, /, **kwargs)
dict(iterable, /, **kwargs)
Arguments
Return Value
- Returns a Python
dictobject
dict Examples
Creating an empty dictionary:
>>> empty_dict = {}
>>> empty_dict
{}
Creating a dictionary using literals:
>>> person = {"name": "Alice", "age": 30, "city": "New York"}
>>> person
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Creating a dictionary using the constructor with keyword arguments:
>>> person = dict(name="Alice", age=30, city="New York")
>>> person
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Accessing dictionary values:
>>> person["name"]
'Alice'
>>> person["age"]
30
Changing values in a dictionary through key assignment:
>>> person["age"] = 31
>>> person["age"]
31
Deleting values from a dictionary:
>>> del person["city"]
>>> person
{'name': 'Alice', 'age': 31}
Iterating over the keys in reverse order, which dictionaries and their view objects have supported since Python 3.8:
>>> person = {"name": "Alice", "age": 30}
>>> list(reversed(person))
['age', 'name']
dict Operators
The merge (|) and update (|=) operators, added in Python 3.9, combine two dictionaries. The | operator returns a new dictionary, while |= updates the left-hand dictionary in place. On keys that appear in both operands, the value from the right-hand operand wins:
>>> defaults = {"theme": "dark", "lang": "en"}
>>> overrides = {"lang": "es"}
>>> defaults | overrides
{'theme': 'dark', 'lang': 'es'}
>>> defaults |= overrides
>>> defaults
{'theme': 'dark', 'lang': 'es'}
dict Methods
| Method | Description |
|---|---|
.clear() |
Removes all items from the dictionary. |
.copy() |
Returns a shallow copy of the dictionary. |
.fromkeys() |
Creates a new dictionary with keys from an iterable and values set to a specified value. |
.get() |
Returns the value for a specified key or a default if the key is not found. |
.items() |
Returns a new view of the dictionary’s items as (key, value) pairs. |
.keys() |
Returns a new view of the dictionary’s keys. |
.pop() |
Removes the specified key and returns its value, or returns a default if the key isn’t found. Raises a KeyError when no default is given. |
.popitem() |
Removes and returns the last key-value pair as a tuple. |
.setdefault() |
Returns the value of a key if it exists; otherwise, inserts the key with a default value. |
.update() |
Updates the dictionary with items from another dictionary or iterable of key-value pairs. |
.values() |
Returns a new view of the dictionary’s values. |
dict Common Use Cases
The most common use cases for the dict include:
- Storing and accessing data organized in key-value pairs
- Managing and organizing data as key-value pairs
- Implementing caches or memoization
- Aggregating counts or other statistics
- Representing JSON-like data structures
dict Real-World Example
Suppose you need to manage a contact list where each contact is identified by a unique name and has associated details like phone number and email. You can use a dictionary to store and manage this data:
>>> contacts = {
... "Alice": {"phone": "123-456-7890", "email": "alice@example.com"},
... "Bob": {"phone": "987-654-3210", "email": "bob@example.com"}
... }
>>> bob_phone = contacts["Bob"]["phone"]
>>> # Update Alice's email
>>> contacts["Alice"]["email"] = "alice.new@example.com"
>>> # Add new contact
>>> contacts["Charlie"] = {
... "phone": "555-555-5555",
... "email": "charlie@example.com"
... }
>>> # Delete existing contact
>>> del contacts["Bob"]
>>> contacts
{
'Alice': {'phone': '123-456-7890', 'email': 'alice.new@example.com'},
'Charlie': {'phone': '555-555-5555', 'email': 'charlie@example.com'}
}
In this example, the dictionary helps efficiently manage and update contact information by leveraging key-value pairs.
Related Resources
Tutorial
Dictionaries in Python
Learn how dictionaries in Python work: create and modify key-value pairs using dict literals, the dict() constructor, built-in methods, and operators.
For additional information on related topics, take a look at the following resources:
- How to Iterate Through a Dictionary in Python (Tutorial)
- Python Dictionary Comprehensions: How and When to Use Them (Tutorial)
- Sorting a Python Dictionary: Values, Keys, and More (Tutorial)
- Custom Python Dictionaries: Inheriting From dict vs UserDict (Tutorial)
- OrderedDict vs dict in Python: The Right Tool for the Job (Tutorial)
- Python Dictionary Iteration: Advanced Tips & Tricks (Course)
- Building Dictionary Comprehensions in Python (Course)
- Using Dictionaries in Python (Course)
- Dictionaries in Python (Quiz)
- Python Dictionary Iteration (Quiz)
- Python Dictionary Comprehensions: How and When to Use Them (Quiz)
- Sorting Dictionaries in Python: Keys, Values, and More (Course)
- Sorting a Python Dictionary: Values, Keys, and More (Quiz)
- Using OrderedDict in Python (Course)