dict
The built-in dict
data type (short for dictionary) represents a collection of key-value pairs, where keys are unique and used to access corresponding values. Dictionaries are mutable, allowing for dynamic data manipulation and growth.
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
Argument | Description |
---|---|
kwargs |
Keyword arguments where the keywords are the keys and the values are the corresponding dictionary values. |
mapping |
A dictionary or any object with a .keys() method. |
iterable |
An iterable of key-value pairs (tuples or iterables of length two). |
Return Value
- Returns a Python
dict
object
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}
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 view object displaying a list of the dictionary’s key-value pairs. |
.keys() |
Returns a view object displaying a list of all the keys. |
.pop() |
Removes the specified key and returns its value. |
.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 view object displaying a list of all the 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
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:
- 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)
- Using Dictionaries in Python (Course)
- Python Dictionaries (Quiz)
- Python Dictionary Iteration: Advanced Tips & Tricks (Course)
- Python Dictionary Iteration (Quiz)
- Python Dictionary Comprehensions: How and When to Use Them (Quiz)
- Sorting Dictionaries in Python: Keys, Values, and More (Course)
- Using OrderedDict in Python (Course)