Python dictionaries are versatile data structures that store key-value pairs. They're mutable, allowing dynamic modifications like adding, updating, or removing items. This flexibility makes dictionaries ideal for organizing and accessing data efficiently.
Dictionaries offer various methods for manipulation and iteration. You can access values using keys, add new pairs, remove items, and iterate through components. Understanding these operations is crucial for effective dictionary usage in Python programming.
Dictionary Fundamentals
Mutability of Python dictionaries
- Dictionaries are mutable data structures in Python allowing for modification after creation
- Key-value pairs can be added, updated, or removed dynamically (adding "age" key, updating "name" value)
- Dictionary size adjusts automatically as key-value pairs are added or removed
- Modifying a dictionary directly updates the existing object without creating a new one
- Assigning a dictionary to another variable creates a reference pointing to the same underlying dictionary object
- Keys in dictionaries must be immutable (immutability of keys)
Dictionary access via keys
- Dictionary values are retrieved using their associated keys enclosed in square brackets
dictionary[key]
- Accessing an existing key returns the corresponding value (
student["name"]
returns "John") - Attempting to access a non-existent key raises a
KeyError
exception
- Accessing an existing key returns the corresponding value (
- Values can be updated by assigning a new value to an existing key
dictionary[key] = new_value
- The
get()
method provides an alternative way to access valuesdictionary.get(key, default_value)
- Returns the value if the key exists, otherwise returns the
default_value
(None
by default)
- Returns the value if the key exists, otherwise returns the
Dictionary Modification
Adding key-value pairs
- New key-value pairs can be added to a dictionary using assignment
dictionary[new_key] = value
- Creates a new key-value pair if the key doesn't exist (
student["age"] = 25
adds "age" key) - Updates the value if the key already exists (
student["name"] = "Jane"
updates "name" value)
- Creates a new key-value pair if the key doesn't exist (
- The
update()
method merges another dictionary or an iterable of key-value pairs into the dictionarydictionary.update(other_dict)
mergesother_dict
intodictionary
dictionary.update(iterable)
merges key-value pairs fromiterable
intodictionary
Removing dictionary items
- The
del
statement removes a specific key-value pair from the dictionarydel dictionary[key]
- Removes the key-value pair if the key exists (
del student["age"]
removes "age" key) - Raises a
KeyError
if the key doesn't exist
- Removes the key-value pair if the key exists (
- The
pop()
method removes a key-value pair and returns the corresponding valuevalue = dictionary.pop(key, default_value)
- Removes and returns the value if the key exists (
age = student.pop("age")
removes and returns the "age" value) - Returns the
default_value
if the key doesn't exist (raisesKeyError
ifdefault_value
not provided)
- Removes and returns the value if the key exists (
- The
popitem()
method removes and returns an arbitrary key-value pair as a tuple(key, value) = dictionary.popitem()
- The
clear()
method removes all key-value pairs, emptying the dictionarydictionary.clear()
Iterating through dictionary components
- The
keys()
method returns a view object containing all the dictionary keysfor key in dictionary.keys():
- Iterating directly over the dictionary
for key in dictionary:
achieves the same result
- Iterating directly over the dictionary
- The
values()
method returns a view object containing all the dictionary valuesfor value in dictionary.values():
- The
items()
method returns a view object containing all the key-value pairs as tuplesfor key, value in dictionary.items():
- Allows simultaneous access to both keys and values during iteration (
for name, grade in student.items():
)
- Allows simultaneous access to both keys and values during iteration (
- Dictionary view objects are dynamic, reflecting any changes made to the dictionary in real-time
Dictionary Performance and Behavior
Efficiency and internal structure
- Dictionaries use a hash function to achieve constant-time average case complexity for key lookups
- The unordered nature of dictionaries allows for efficient insertion and deletion operations
- Lookup efficiency in dictionaries is typically O(1), making them suitable for large datasets
Specialized dictionary types
- The defaultdict is a subclass of dict that automatically initializes new keys with a default value