Dictionaries
A dictionary
is a data set of key-value pairs. It maps pieces of data to each other and allows quick access to values associated with keys.
In Python, dictionaries are dynamic and mutable, meaning they can change in size or content.
Note: As of Python version 3.7, dictionaries maintain insertion order. This behavior was not guaranteed in previous versions.
Creating a Dictionary
Syntax for creating an empty dictionary:
dictionary_name = {}
The dict()
function can also be used:
dictionary_name = dict()
Syntax for creating a dictionary with entries:
dictionary_name = { key1: value1, key2: value2, key3: value3, ... }
Each item is a key-value pair, separated by a comma.
Keys must be immutable types, such as numbers and strings. Using mutable types like lists as keys will raise a TypeError
.
Values can be of any type, including strings, numbers, lists, and even dictionaries.
Example
# Create a dictionarycoffee_shop = { "cold brew": 3.50, "latte": 4.25, "cappucino": 3.99 }# Print the dictionaryprint(coffee_shop)
Output:
{'cold brew': 3.5, 'latte': 4.25, 'cappucino': 3.99}
Accessing Items in a Dictionary
Access a value by referencing its key:
coffee_shop = { "cold brew": 3.50, "latte": 4.25, "cappucino": 3.99 }print(coffee_shop["cold brew"])
Output:
3.5
Attempting to retrieve a value with a non-existent key raises a KeyError
. Assigning a value to a new key adds a new pair, while assigning to an existing key updates its value.
Adding Items to a Dictionary
To add an item:
dictionary_name[new_key] = new_value
Example
coffee_shop = { "cold brew": 3.50, "latte": 4.25, "cappucino": 3.99 }coffee_shop["espresso"] = 4.72print(coffee_shop)
Output:
{'cold brew': 3.5, 'latte': 4.25, 'cappucino': 3.99, 'espresso': 4.72}
Changing Items in a Dictionary
To change a value:
coffee_shop = { "cold brew": 3.50, "latte": 4.25, "cappucino": 3.99 }coffee_shop["cold brew"] = 3.18print(coffee_shop)
Output:
{'cold brew': 3.18, 'latte': 4.25, 'cappucino': 3.99}
Removing Items from a Dictionary
Use the del
statement:
del dictionary_name[key]
Example
coffee_shop = { "cold brew": 3.50, "latte": 4.25, "cappucino": 3.99 }del coffee_shop["latte"]print(coffee_shop)
Output:
{'cold brew': 3.5, 'cappucino': 3.99}
Iterating a Dictionary
Common methods for iteration:
.keys()
: Accesses dictionary keys..values()
: Accesses dictionary values..items()
: Accesses key-value pairs.
Syntax
dictionary_name.keys()dictionary_name.values()dictionary_name.items()
Codebyte Example
Output:
cold brewlattecappucino3.54.253.99('cold brew', 3.5)('latte', 4.25)('cappucino', 3.99)cold brew 3.5latte 4.25cappucino 3.99
Frequently Asked Questions
1. Are dict()
and {}
the same?
Yes. Both create a dictionary, but differ in syntax:
{}
creates an empty dictionary directly.dict()
creates an empty dictionary and can also take keyword arguments or an iterable of key-value pairs.
2. How do I merge two dictionaries in Python?
Use the .update()
method:
dict1.update(dict2)
3. How to clear a dictionary in Python?
Use the .clear()
method:
dictionary_name.clear()
Dictionaries
- .clear()
- Removes all entries in a dictionary.
- .copy()
- Returns a copy of a dictionary.
- .fromkeys()
- Returns a dictionary with the specified keys.
- .get()
- Retrieves the value for a specified key from a dictionary with an optional default value.
- .items()
- Returns a list of tuples for each key-value pair in a dictionary.
- .keys()
- Returns a list of keys for a dictionary.
- .pop()
- Returns the value of a specified key, then removes the key-value pair from a dictionary.
- .popitem()
- Returns the last inserted key-value pair from a dictionary as a tuple, and removes the entry.
- .setdefault()
- Returns the value of a specified key. If the key does not exist, it is inserted with the specified value.
- .update()
- Updates the dictionary with key-value pairs from another dictionary or iterable, overwriting existing keys if they exist.
- .values()
- Returns a view of values for a dictionary.
All contributors
- StevenSwiniarski
- Anonymous contributor
- brbeck1902
- christian.dinh
- Sriparno08
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours