Dictionaries are a critical built-in data type in Python used to store data in key-value pairs. Unlike sequences like lists and tuples which store data by index position, dictionaries allow you to access values using a key.
In this comprehensive guide, you‘ll learn about 10 commonly used Python dictionary methods with clear examples and sample code. By the end, you‘ll have the knowledge to efficiently perform operations like accessing, adding or deleting dictionary items in your Python projects.
Why Dictionaries are Useful in Python
Before jumping into the methods, let‘s discuss why dictionaries are such popular built-in data structures in Python:
-
Fast lookup time – Dictionaries utilize hashing to enable O(1) lookup time on average. This makes retrieval very fast compared to O(n) time for lists.
-
Flexible data storage – Dictionaries allow storing data in intuitive key-value pairs without order, making them very adaptable. You can mix data types unlike arrays.
-
Real-world mapping – Key-value pairs make it easy to model real-world mappings like user profile data, caches, JSON storage etc.
Let‘s now dive deeper into some common use cases where dictionaries shine…
Example 1: User Profile Storage
user = {
‘name‘: ‘John‘,
‘id‘: 12345,
‘dob‘: ‘01/01/2000‘,
‘hobbies‘: [‘reading‘, ‘hiking‘]
}
We can store relevant user data like name, date of birth etc in a dictionary by assigning keys like ‘name‘, ‘dob‘. Makes retrieval easy:
print(user[‘name‘]) # John
Example 2: Word Counter
text = "Python is awesome! Python has great dictionary methods."
word_count = {}
for word in text.split():
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(word_count)
# {‘Python‘: 2, ‘is‘: 1, ...}
By storing counts in a dictionary, we can efficiently track word frequencies.
Now that you know why dictionaries are indispensable in Python, let‘s explore them further!
Python Dictionary Methods Overview
Before covering the methods, we‘ll do a quick recap of Python dictionary basics…
Python Dictionaries 101
- Dictionaries consist of key-value pairs enclosed in curly braces
{}
- Keys can be strings, numbers or tuples (must be hashable)
- Values can be any arbitrary Python object
- Dictionaries are unordered (elements stored in no particular order)
Let‘s initialize an empty dictionary:
person = {}
We can add some key-value pairs like below:
person[‘name‘] = ‘John‘
person[‘age‘] = 20
person[‘hobbies‘] = [‘Guitar‘, ‘Reading‘]
Let‘s now get into dictionary methods!
1. Get Dictionary Keys: keys()
The keys()
method returns a dict_keys view object containing all the keys in the dictionary. For example:
person = {‘name‘: ‘John‘, ‘age‘: 20}
person.keys()
# dict_keys([‘name‘, ‘age‘])
We can iterate over the keys easily:
for key in person.keys():
print(key)
# name
# age
Use cases:
- Checking if key exists in dictionary
- Iterating over keys
Let‘s look at some more examples…
2. Get Dictionary Values: values()
The values()
method returns a dict_values view object containing all the values in the dictionary.
For example:
person = {‘name‘: ‘John‘, ‘age‘: 20}
person.values()
# dict_values([‘John‘, 20])
We can sum values easily:
vals = person.values()
sum(vals) # 20
Use cases:
- Iterating over values
- Aggregate operations on values
Now let‘s learn how to access key-value pairs…
3. Get Key-Value Pairs: items()
The items()
dictionary method returns a dict_items object which is an array of tuples for each key-value pair:
person = {‘name‘: ‘John‘, ‘age‘: 20}
person.items()
# dict_items([(‘name‘, ‘John‘), (‘age‘, 20)])
We can iterate over the pairs:
for key, val in person.items():
print(f"{key}: {val}")
Furthermore, we can unpack pairs into variables:
key, val = person.items()[1]
print(key) # age
print(val) # 20
Use cases:
- Iterating over key-value pairs
- Unpacking pairs into variables
- Converting dictionary into list of tuples
Next up, let‘s clone our dictionary…
4. Get Shallow Copy: copy()
We often need to duplicate a dictionary. Using copy()
creates a shallow copy of the dictionary.
For example:
original = {‘name‘: ‘John‘}
duplicate = original.copy()
duplicate[‘name‘] = ‘Jane‘
original
# {‘name‘: ‘John‘}
duplicate
# {‘name‘: ‘Jane‘}
Changes made to the copy do not affect original.
Let‘s learn how copy()
differs from direct assignment:
copy = original # simple assignment
copy[‘name‘] = ‘Jane‘
original # {‘name‘: ‘Jane‘}
Here both original
and copy
refer to same dictionary. Changes to one affects the other since only the reference was copied, not dictionary itself.
Use cases:
- Duplicating dictionaries safely without aliasing
- Preserving original dictionary while modifying copy
So when should you use copy()
? Let‘s find out…
5. Set Default Value: setdefault()
The setdefault()
method is used to set a default value for a missing key and prevent KeyError
exceptions.
For example, trying to access a missing key raises a KeyError
:
person = {‘name‘: ‘John‘}
person[‘age‘]
# KeyError: ‘age‘
We can avoid this by using setdefault()
:
person.setdefault(‘age‘, 20) # 20
person
# {‘name‘: ‘John‘, ‘age‘: 20}
Since ‘age‘
key was missing, setdefault()
added it with default value 20
.
Here are some key things to know about setdefault()
:
- Returns existing value if key already exists
- Adds key with
None
as default if value not provided - Added key remains in dictionary
In summary, setdefault()
provides a safe way to retrieve values from dictionaries by handling missing keys.
6. Get Value for Key: get()
Similar to setdefault()
, the get()
method retrieves values from a dictionary by key. If key does not exist, get()
behaves differently:
- It does not add missing key to the dictionary
- Returns
None
or a custom default value
Example usage:
person = {‘name‘: ‘John‘}
person.get(‘age‘) # None
person.get(‘age‘, 20) # 20
person # No change
Comparing get()
and setdefault()
:
get() |
setdefault() |
|
---|---|---|
Retrieves key if exists | Yes | Yes |
Adds key if missing | No | Yes |
Custom default value | Yes | Yes |
Default if none specified | None |
None |
So in summary, use:
get()
to safely retrieve valuessetdefault()
to set defaults for missing keys
Now let‘s see how to update dictionary contents…
7. Update Dictionary: update()
We can update the contents of a dictionary using another dictionary with the update()
method.
For example:
person = {‘name‘: ‘John‘, ‘age‘: 20}
extra_details = {‘hobbies‘: [‘reading‘, ‘hiking‘], ‘address‘: ‘123 Main St‘}
person.update(extra_details)
person
# {‘name‘: ‘John‘, ‘age‘: 20, ‘hobbies‘: [‘reading‘, ‘hiking‘], ‘address‘: ‘123 Main St‘}
We merged extra_details
dictionary into person
dictionary with .update()
.
Use cases:
- Merging contents from multiple dictionaries
- Overriding values with updates
Later we‘ll also cover removing items – but first, let‘s look at deleting the last added item with popitem()
…
8. Remove Last Item: popitem()
The popitem()
dictionary method removes and returns the last inserted key-value pair as a tuple:
person = {‘name‘: ‘John‘, ‘age‘: 20}
person[‘id‘] = 1234
person[‘id2‘] = 4321
person.popitem()
# (‘id2‘, 4321)
person
# {‘name‘: ‘John‘, ‘age‘: 20, ‘id‘: 1234}
Notice how id2
key-value added last was removed.
Use cases:
- Removing latest item in dictionaries like caches
- Reverting recent changes
For more flexibility removing items, you can use pop()
…
9. Remove Item by Key: pop()
While popitem()
always deletes the last inserted item, the pop()
method deletes dictionary item for a specific key.
Syntax:
dict.pop(key)
This removes key-value pair for given key and returns value.
Example:
person = {‘name‘: ‘John‘, ‘age‘: 21}
value = person.pop(‘age‘)
print(value) # 21
print(person) # {‘name‘: ‘John‘}
Using pop()
, we deleted the item with key ‘age‘
and stored value.
Use cases:
- Deleting specific item from dictionary
- Storing deleted value for future use
What if we pass an invalid key?
person.pop(‘invalid‘)
# KeyError
We get a KeyError
. So key must exist.
Finally, let‘s learn how to clear all contents…
10. Clear Dictionary: clear()
The clear()
dictionary method deletes all items from dictionary.
For example:
person = {‘name‘: ‘John‘, ‘age‘: 20}
person.clear()
print(person) # {}
Dictionary is now empty!
Use cases:
- Wiping all dictionary contents
- Resetting state
Let‘s wrap up with a quick summary…
Summary of Python Dictionary Methods
Here‘s a concise overview of all the dictionary methods we learned:
Method | Description |
---|---|
keys() |
Get list of keys |
values() |
Get list of values |
items() |
Get list of key-value tuples |
copy() |
Shallow copy |
setdefault(key, default) |
Set default if key missing |
get(key, default) |
Get value safely |
update(dict2) |
Update dict with dict2 |
popitem() |
Remove last item |
pop(key) |
Remove item by key |
clear() |
Clear all items |
You‘ve now learned how to leverage built-in dictionary methods in Python to efficiently access, modify and manage dictionary contents!
Some next things to learn are dictionary comprehensions and ordering in Python 3.7+.
I hope you enjoyed this guide to Python dictionary methods. Happy coding! ????