Dictionaries in Python are powerful, flexible data structures that store key-value pairs. Python provides a robust set of built-in methods to work with dictionaries efficiently.
In this guide, we’ll cover all standard dictionary methods with examples for each, helping you become fluent in handling dictionaries in your Python programs.
1. clear()
Removes all elements from the dictionary.
person = {'name': 'Alice', 'age': 30}
person.clear()
print(person)
Output: {}
2. copy()
Returns a shallow copy of the dictionary.
original = {'a': 1, 'b': 2}
duplicate = original.copy()
print(duplicate)
Output: {'a': 1, 'b': 2}
3. fromkeys()
Creates a new dictionary from a sequence of keys, assigning a common value.
keys = ['id', 'name', 'age']
defaults = dict.fromkeys(keys, 'N/A')
print(defaults)
Output: {'id': 'N/A', 'name': 'N/A', 'age': 'N/A'}
4. get()
Returns the value for the specified key. If the key is not found, returns None
or a default value.
user = {'username': 'john'}
print(user.get('email')) # None
print(user.get('email', 'unknown')) # 'unknown'
Output:
None
unknown
5. items()
Returns a view object that displays a list of dictionary’s key-value tuple pairs.
data = {'x': 10, 'y': 20}
for key, value in data.items():
print(f"{key} = {value}")
Output:
x = 10
y = 20
6. keys()
Returns a view object of all keys in the dictionary.
info = {'brand': 'Ford', 'model': 'Mustang'}
print(list(info.keys()))
Output: ['brand', 'model']
7. values()
Returns a view object of all values in the dictionary.
info = {'brand': 'Ford', 'model': 'Mustang'}
print(list(info.values()))
Output: ['Ford', 'Mustang']
8. pop()
Removes the specified key and returns its value.
settings = {'theme': 'dark', 'font': 'Arial'}
removed = settings.pop('font')
print(removed)
print(settings)
Output:
Arial
{'theme': 'dark'}
9. popitem()
Removes and returns the last inserted key-value pair (as a tuple).
book = {'title': '1984', 'author': 'Orwell'}
last_entry = book.popitem()
print(last_entry)
print(book)
Output:
('author', 'Orwell')
{'title': '1984'}
In Python versions < 3.7,
popitem()
removes a random item.
10. setdefault()
Returns the value of a key if it exists. If not, inserts the key with a specified default value.
profile = {'name': 'Jane'}
email = profile.setdefault('email', '[email protected]')
print(profile)
Output: {'name': 'Jane', 'email': '[email protected]'}
11. update()
Updates the dictionary with elements from another dictionary or iterable of key-value pairs.
user = {'name': 'Tom'}
user.update({'age': 25, 'city': 'Paris'})
print(user)
Output: {'name': 'Tom', 'age': 25, 'city': 'Paris'}
Summary Table
Method | Description |
---|---|
clear() |
Removes all items from the dictionary |
copy() |
Returns a shallow copy |
fromkeys() |
Creates a new dictionary from given keys and a default value |
get() |
Returns value for key, or default/None |
items() |
Returns view of key-value pairs |
keys() |
Returns view of all keys |
values() |
Returns view of all values |
pop() |
Removes and returns a value by key |
popitem() |
Removes and returns the last inserted key-value pair |
setdefault() |
Returns value for key, or inserts and returns default |
update() |
Updates dictionary with another dictionary or iterable of key-value pairs |
Final Thoughts
Python’s dictionary methods offer a flexible way to manage mappings between keys and values. Whether you’re storing user settings, managing configurations, or implementing caches, understanding these methods is vital for effective programming.