Dictionary Methods
Essential dictionary operations and methods
#dict #dictionary #methods #data-structures
Dictionary Methods
Common dictionary operations for working with key-value pairs.
Basic Operations
# Create and access
user = {'name': 'Alice', 'age': 30, 'city': 'NYC'}
print(user['name']) # Alice
print(user.get('email', 'N/A')) # N/A (default value)
# Add/update
user['email'] = 'alice@example.com'
user.update({'age': 31, 'country': 'USA'})
Useful Methods
# Keys, values, items
print(user.keys()) # dict_keys(['name', 'age', 'city', 'email'])
print(user.values()) # dict_values(['Alice', 31, 'NYC', 'alice@example.com'])
print(user.items()) # dict_items([('name', 'Alice'), ...])
# Pop and setdefault
age = user.pop('age') # Remove and return
user.setdefault('role', 'user') # Set if not exists
# Merge dictionaries (Python 3.9+)
defaults = {'theme': 'dark', 'lang': 'en'}
settings = {**defaults, **user}
Discover another handy tool from EditPDF.pro