What is a dictionary in Python?
A Python dictionary is an unordered collection of data values, used to store data values like a map. Unlike other data types that hold only a single value as an element, dictionaries hold key:value pairs. Dictionaries are mutable, meaning they can be changed after creation, and are optimized for retrieving values when the key is known.
What is a Dictionary?
Dictionaries are Python's implementation of a hash table type. They consist of a collection of key-value pairs. Each key maps to a specific value, allowing for efficient data retrieval. Keys must be unique and immutable (like strings, numbers, or tuples), while values can be of any data type and can be duplicated.
They are often used to store related pieces of information, such as a person's name, age, and city, where each piece of information has a descriptive label (the key).
Creating Dictionaries
Dictionaries are created by placing a comma-separated list of key:value pairs inside curly braces {}. An empty dictionary can be created with just empty curly braces.
# Empty dictionary
my_dict = {}
print(my_dict)
# Dictionary with integer keys
student = {
101: 'Alice',
102: 'Bob',
103: 'Charlie'
}
print(student)
# Dictionary with mixed keys and values
person = {
'name': 'John Doe',
'age': 30,
'is_student': False,
'courses': ['Math', 'Science']
}
print(person)
Accessing Dictionary Elements
Values can be accessed using their respective keys inside square brackets [] or by using the get() method. The get() method is safer as it returns None (or a default value if specified) if the key is not found, instead of raising a KeyError.
person = {
'name': 'Jane Doe',
'age': 25,
'city': 'New York'
}
# Accessing using square brackets
print(person['name']) # Output: Jane Doe
# Accessing using get() method
print(person.get('age')) # Output: 25
print(person.get('country')) # Output: None
print(person.get('country', 'USA')) # Output: USA (default value)
Modifying and Deleting Elements
Dictionaries are mutable, allowing you to add new key-value pairs, update existing values, and remove elements.
my_settings = {
'theme': 'dark',
'notifications': True
}
# Adding a new key-value pair
my_settings['language'] = 'en'
print(my_settings)
# Updating an existing value
my_settings['theme'] = 'light'
print(my_settings)
# Deleting a key-value pair using del
del my_settings['notifications']
print(my_settings)
# Deleting a key-value pair using pop()
# pop() also returns the value of the removed item
removed_language = my_settings.pop('language')
print(my_settings)
print(removed_language)
# popitem() removes and returns an arbitrary (last inserted in Python 3.7+) key-value pair
last_item = my_settings.popitem()
print(my_settings)
print(last_item)
Common Dictionary Methods
Python dictionaries come with several built-in methods to interact with their contents.
keys(): Returns a new view of the dictionary's keys.values(): Returns a new view of the dictionary's values.items(): Returns a new view of the dictionary's key-value pairs as tuples.update(other): Updates the dictionary with the key-value pairs fromother, overwriting existing keys.clear(): Removes all items from the dictionary.copy(): Returns a shallow copy of the dictionary.
Key Characteristics
- Unordered (pre-Python 3.7): Order of elements is not guaranteed. From Python 3.7 onwards, dictionaries maintain insertion order.
- Mutable: Dictionaries can be changed after they are created (add, remove, or modify elements).
- Key-Value Pairs: Data is stored as pairs where each unique key maps to a value.
- Keys must be Unique: No two keys can be the same within a single dictionary.
- Keys must be Immutable: Keys can be strings, numbers, or tuples (containing only immutable elements), but not lists or other mutable objects.
Understanding Key Immutability
The requirement for keys to be immutable is fundamental to how dictionaries work internally. Dictionaries use a hashing mechanism to store and retrieve data efficiently. Mutable objects can change their hash value, which would break the ability of the dictionary to find the key correctly. Therefore, mutable types like lists, sets, or other dictionaries cannot be used as keys.