Python Dictionaries
What is a Dictionary?
A dictionary is a built-in data structure in Python that stores data as key-value pairs. It is mutable, allows fast lookups by key, and can hold heterogeneous data types.
Dictionaries are defined with curly braces `{}` containing key:value pairs, or by using the `dict()` constructor.
Example
# Creating dictionaries
person = {"name": "John", "age": 30, "city": "New York"}
empty_dict = {}
# Using dict() constructor
person2 = dict(name="Jane", age=25, city="London")
print(person)
print(person2)
Output
{'name': 'John', 'age': 30, 'city': 'New York'} {'name': 'Jane', 'age': 25, 'city': 'London'}
Dictionary Characteristics
- Insertion order is preserved (Python 3.7+).
- Mutable: You can add, remove, and update key-value pairs.
- Keys must be immutable (e.g., strings, numbers, or tuples with immutable elements).
- Values can be any type (strings, numbers, lists, other dictionaries, etc.).
- Keys must be unique; assigning an existing key overwrites its value.
Dictionary Use Cases
Dictionaries are useful for:
- Storing related information such as object properties
- Counting occurrences of items (e.g., word frequencies)
- Mapping relationships between values (e.g., IDs to names)
- Caching or memoizing function results
- Managing configuration and settings