Python Dictionary Methods
Python dictionaries are one of the most versatile and powerful data structures in the language. This page provides a comprehensive reference for all Python dictionary methods with examples, explanations, and time complexity analysis.
Creation and Basic Operations
Dictionary Creation
# Using curly braces person = {'name': 'John', 'age': 30, 'city': 'New York'} # Using dict() constructor person = dict(name='John', age=30, city='New York') # From a list of tuples person = dict([('name', 'John'), ('age', 30), ('city', 'New York')]) # Dictionary comprehension squares = {x: x**2 for x in range(6)} # Result: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Time Complexity: O(n) where n is the number of key-value pairs
Accessing Values
person = {'name': 'John', 'age': 30, 'city': 'New York'} # Using key name = person['name'] # 'John' # Using get() method (safer if key might not exist) email = person.get('email') # Returns None email = person.get('email', 'Not available') # Returns 'Not available'
Time Complexity: O(1) average case
Modification Methods
dict.update()
# Add or update multiple key-value pairs person = {'name': 'John', 'age': 30} person.update({'age': 31, 'city': 'New York'}) # Result: {'name': 'John', 'age': 31, 'city': 'New York'}
Time Complexity: O(n) where n is the length of the argument
dict.setdefault()
# Get value if key exists, otherwise insert key with a default value person = {'name': 'John', 'age': 30} city = person.setdefault('city', 'Unknown') # person = {'name': 'John', 'age': 30, 'city': 'Unknown'} # city = 'Unknown'
Time Complexity: O(1) average case
Modification Methods
dict.update()
# Add or update multiple key-value pairs person = {'name': 'John', 'age': 30} person.update({'age': 31, 'city': 'New York'}) # Result: {'name': 'John', 'age': 31, 'city': 'New York'}
Time Complexity: O(n) where n is the length of the argument
dict.setdefault()
# Get value if key exists, otherwise insert key with a default value person = {'name': 'John', 'age': 30} city = person.setdefault('city', 'Unknown') # person = {'name': 'John', 'age': 30, 'city': 'Unknown'} # city = 'Unknown'
Time Complexity: O(1) average case
dict.pop()
# Remove key and return its value person = {'name': 'John', 'age': 30, 'city': 'New York'} age = person.pop('age') # person = {'name': 'John', 'city': 'New York'} # age = 30 # With default value if key doesn't exist email = person.pop('email', 'No email found') # email = 'No email found'
Time Complexity: O(1) average case
dict.popitem()
# Remove and return the last inserted key-value pair person = {'name': 'John', 'age': 30, 'city': 'New York'} last_item = person.popitem() # person = {'name': 'John', 'age': 30} # last_item = ('city', 'New York')
Time Complexity: O(1)
dict.clear()
# Remove all items from the dictionary person = {'name': 'John', 'age': 30, 'city': 'New York'} person.clear() # Result: {}
Time Complexity: O(1)
View Methods
dict.keys()
person = {'name': 'John', 'age': 30} keys = person.keys() # Result: dict_keys(['name', 'age']) # Convert to list if needed keys_list = list(person.keys()) # Result: ['name', 'age']
Time Complexity: O(1) for creating view, O(n) for conversion
dict.values()
person = {'name': 'John', 'age': 30} values = person.values() # Result: dict_values(['John', 30]) # Convert to list if needed values_list = list(person.values()) # Result: ['John', 30]
Time Complexity: O(1) for creating view, O(n) for conversion
dict.items()
person = {'name': 'John', 'age': 30} items = person.items() # Result: dict_items([('name', 'John'), ('age', 30)]) # Iterate through key-value pairs for key, value in person.items(): print(key, value) # Output: # name John # age 30
Time Complexity: O(1) for creating view, O(n) for iteration
Other Methods
dict.copy()
# Create a shallow copy person = {'name': 'John', 'age': 30} person_copy = person.copy() # Both dictionaries have the same content # but are different objects
Time Complexity: O(n)
dict.fromkeys()
# Create a new dictionary with keys from iterable keys = ['name', 'age', 'city'] person = dict.fromkeys(keys, 'Unknown') # Result: {'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'}
Time Complexity: O(n)
Dictionary Membership
in Operator
person = {'name': 'John', 'age': 30, 'city': 'New York'} # Check if key exists if 'name' in person: print("Name found:", person['name']) # Check if key doesn't exist if 'email' not in person: print("Email not found")
Time Complexity: O(1) average case
Time Complexity Summary
Operation | Average Case | Worst Case | Notes |
---|---|---|---|
Access by key (d[key]) | O(1) | O(n) | Worst case happens with hash collisions |
Set value (d[key] = value) | O(1) | O(n) | Worst case happens with hash collisions |
Delete key (del d[key]) | O(1) | O(n) | Worst case happens with hash collisions |
get(key[, default]) | O(1) | O(n) | Safer than direct key access |
update([other]) | O(n) | O(n) | n is the length of the other dictionary |
keys(), values(), items() | O(1) | O(1) | Returns view objects |
copy() | O(n) | O(n) | Creates a shallow copy |
pop(key[, default]) | O(1) | O(n) | Removes item and returns value |
popitem() | O(1) | O(1) | Removes last inserted item |
clear() | O(1) | O(1) | Removes all items |
fromkeys(seq[, value]) | O(n) | O(n) | n is the length of the sequence |
in operator | O(1) | O(n) | Checks if key exists |
Dictionary Best Practices
- Use
get()
method instead of direct key access to avoid KeyError exceptions - Use dictionary comprehensions for creating dictionaries from existing data
- When iterating, use
items()
to access both keys and values - Remember that dictionaries are ordered (Python 3.7+) but don't rely on this for older Python versions
- Use dictionary unpacking (
**dict
) for combining dictionaries in Python 3.5+ - For dictionaries with default values, consider using
collections.defaultdict
On This Page
- Dictionary Creation
- Accessing Values
- Modification Methods
- View Methods
- Utility Methods
- Dictionary Membership
- Time Complexity
Related Content
- Dictionary Performance
Learn about dictionary time complexity and optimization
- Best Practices
Coding standards for effective dictionary usage
- Advanced Techniques
Explore defaultdict, Counter, and OrderedDict