In this post, we will examine 10 Python dictionary methods every Python developer should be familiar with.
What is a Python Dictionary?
A Python dictionary is a fundamental data structure that stores a collection of key-value pairs. Each key is unique and serves as an identifier for its associated value.
Dictionaries are unordered, meaning they don’t maintain any specific order of elements, and they are mutable, allowing for dynamic modification of their contents.
Python dictionaries are incredibly versatile, making them suitable for a wide range of tasks, such as storing and retrieving data efficiently, representing complex data structures, and performing lookups and data transformations.
They are implemented as hash tables, which ensures fast access to values based on their keys, even for large datasets. Dictionaries are a crucial tool for developers in Python, offering a flexible way to manage and manipulate data in their programs.
Some Uses of Python Dictionary
- Data Retrieval: Dictionaries are excellent for quick data retrieval when you have a unique identifier (the key). For example, you can use a dictionary to store and access information about individuals using their names as keys.
- Counting and Frequency: Dictionaries are useful for counting occurrences of items in a dataset. You can use items as keys and increment their corresponding values to keep track of frequencies, making them handy for tasks like word frequency analysis.
- Configuration Settings: Dictionaries can store configuration settings for applications. Keys can represent setting names, and values can store the configuration options. This makes it easy to change and retrieve settings as needed.
- Caching: Dictionaries can be used as a cache to store expensive or frequently used results of function calls, database queries, or other computations. This can improve the performance of your programs.
- Mapping: Dictionaries are often used to create mappings between two sets of data. For example, you can map employee IDs to employee names or postal codes to city names.
- Graphs and Trees: Dictionaries can represent graph or tree structures by using keys as nodes and values as edges or child nodes, allowing for the efficient traversal of these structures.
- Lookup Tables: Dictionaries can serve as lookup tables, where keys represent codes or identifiers, and values provide corresponding information, like translating country codes to country names.
Now that we know what a Python dictionary is and its uses, let us now look at 10 dictionary methods Python developers should know.
First, though, we will create an example dictionary.
Create Dictionary
Below is an example of a Python dictionary data structure:
# create dictionary
my_dict = dict(Names = ["Amaka", "Chad", "Kemi", "Jack", "Tim"],
Age = [22, 24, 30, 27, 32])
print(my_dict)
# {'Names': ['Amaka', 'Chad', 'Kemi', 'Jack', 'Tim'], 'Age': [22, 24, 30, 27, 32]}
With the example dictionary created, let us now examine the 10 methods.
- Get Dictionary Keys | keys()
print(my_dict.keys())
# dict_keys(['Names', 'Age'])
The keys() method returns a view of all keys in the dictionary.
2. Get Dictionary Values | values()
# get values
print(my_dict.values())
# dict_values([['Amaka', 'Chad', 'Kemi', 'Jack', 'Tim'], [22, 24, 30, 27, 32]])
The values() method returns a view of all values in the dictionary.
3. Get Key Values | get()
# get age values
ages = my_dict.get("Age")
# [22, 24, 30, 27, 32]
The get() method returns the value associated with the specified key, or a default value if the key is not found.
Another way to get the values of a key is to subset the dictionary using the key of interest.
print(my_dict["Age"])
# [22, 24, 30, 27, 32]
4. Get All Items in Dictionary | items()
# get all items
print(my_dict.items())
# dict_items([('Names', ['Amaka', 'Chad', 'Kemi', 'Jack', 'Tim']), ('Age', [22, 24, 30, 27, 32])])
The items() method returns a view of all key-value pairs in the dictionary as tuples.
5. Make Copy of Dictionary | copy()
# make copy of dictionary
copy = my_dict.copy()
print(copy)
# {'Names': ['Amaka', 'Chad', 'Kemi', 'Jack', 'Tim'], 'Age': [22, 24, 30, 27, 32]}
The copy() method returns a shallow copy of the dictionary.
6. Clear Dictionary | clear()
# clear dictionary content
empty_dict = my_dict.clear()
print(empty_dict)
# None
The clear() method removes all key-value pairs from the dictionary, making it empty.
7. Update Dictionary | update()
# update dicitonary with another dictionary
another_dict = {"Count":[1,2,3,4,5]}
my_dict.update(another_dict)
print(my_dict)
# {'Names': ['Amaka', 'Chad', 'Kemi', 'Jack', 'Tim'], 'Age': [22, 24, 30, 27, 32], 'Count': [1, 2, 3, 4, 5]}
The update() method updates the dictionary with key-value pairs from another dictionary or an iterable of key-value pairs.
8. Remove Item with Specified Key | pop()
# remove an item with a specified key and return its values
values = my_dict.pop("Age")
print(values)
print(my_dict)
# [22, 24, 30, 27, 32]
# {'Names': ['Amaka', 'Chad', 'Kemi', 'Jack', 'Tim']}
The pop() method removes the item with the specified key and returns its value. If the key is not found, it returns the default value or raises a KeyError.
9. Remove Last Item in Dictionary | popitem()
# remove the last item in a dictionary and return its key-value pair as a tuple.
tup = my_dict.popitem()
print(tup)
print(my_dict)
# ('Age': [22, 24, 30, 27, 32])
# {'Names': ['Amaka', 'Chad', 'Kemi', 'Jack', 'Tim']}
The popitem() method removes the last item in the dictionary and returns its key-value pair as a tuple.
10. Set Dictionary Key-Value Pairs | setdefault()
# create nested list
nested_list = [["Amaka", "Chad", "Kemi", "Jack", "Tim"],[22, 24, 30, 27, 32]]
print(nested_list)
# [['Amaka', 'Chad', 'Kemi', 'Jack', 'Tim'], [22, 24, 30, 27, 32]]
new_dict = dict()
for i in nested_list[0]:
for j in nested_list[1]:
new_dict.setdefault(i,j)
print(new_dict)
# {'Amaka': 22, 'Chad': 22, 'Kemi': 22, 'Jack': 22, 'Tim': 22}
The setdefault() method is used to set the default key-value pairs of a dictionary.
In the above code, we turned a nested list into a dictionary by looping through the items in each list and passing the loop variables to the setdefault() method to create the dictionary’s key-value pairs.
Python dictionary is one of the easiest-to-use data structures in Python and it is very popular with Python developers.
I hope this post has helped you get familiar with Python dictionary methods.