Published on

Top 10 Python Dictionary operations : Complete List

Authors

Table of contents

Introduction

Python dictionaries are a versatile and essential data structure used for storing and retrieving key-value pairs. In this blog post, we will discuss the top 10 Python dictionary operations that you should know.

Creating a dictionary

To create a dictionary in Python, we use curly braces {} and separate each key-value pair with a colon :. For example, let's create a dictionary that stores the prices of some fruits:

prices = {
    'apple': 1.99,
    'banana': 0.99,
    'orange': 1.49
}

Alternatively, we can use the built-in dict() function to create a dictionary:

prices = dict(
    apple=1.99,
    banana=0.99,
    orange=1.49
)

Get values from dictionary

To access a value in a dictionary, we use the key associated with the value using the square brackets []. For example, let's access the price of an apple:

apple_price = prices['apple']
print(apple_price) # Output: 1.99

If the key does not exist in the dictionary, Python will raise a KeyError exception.

To avoid exceptions in case the key does not exists, we can also access the value using the key using get() method. For example, let's access the price of an apple again using get() method.

apple_price = prices.get("apple")
print(apple_price) # Output: 1.99

In case, if the key does not exists this method will return None value.

apple_price = prices.get("avocado")
print(apple_price) # Output: None

Adding a new key-value pair to a dictionary

To add a new key-value pair to an existing dictionary, we can use the square brackets [] and the assignment operator =. For example, let's add the price of a pear:

prices['pear'] = 2.49
print(prices) # Output: {'apple': 1.99, 'banana': 0.99, 'orange': 1.49, 'pear': 2.49}

Removing a key-value pair from a dictionary

To remove a key-value pair from a dictionary, we can use the del statement or the pop() method. For example, let's remove the price of an orange using the del statement:

del prices['orange']
print(prices) # Output: {'apple': 1.99, 'banana': 0.99, 'pear': 2.49}

Alternatively, we can use the pop() method to remove a key-value pair and return the value:

orange_price = prices.pop('orange')
print(orange_price) # 1.49

Note : Both of these methods will throw an exception if the key does not exists in the dictionary.

Checking if a key exists in a dictionary

To check if a key exists in a dictionary, we can use the in keyword or the get() method. For example, let's check if the price of a banana is in the prices dictionary:

if 'banana' in prices:
    print('The price of a banana is', prices['banana'])
else:
    print('Bananas are not in stock')

Iterating over a dictionary

To iterate over a dictionary, we can use a for loop and the items() method to access both the keys and values of each key-value pair. For example, let's iterate over the prices dictionary and print the name and price of each fruit:

for fruit, price in prices.items():
    print(fruit, 'costs', price, 'dollars')

Updating a dictionary

To update a dictionary with new key-value pairs or by modifying the values associated with existing keys, we can use the update() method. For example, let's add the prices of some more fruits to the prices dictionary:

more_prices = {'grape': 2.99, 'kiwi': 1.79}
prices.update(more_prices)
print(prices) # Output: {'apple': 1.99, 'banana': 0.99, 'pear': 2.49, 'grape': 2.99, 'kiwi': 1.79}

If a key already exists in the dictionary, its value will be updated with the new value.

Sorting a dictionary

To sort a dictionary by key or value, we can use the built-in sorted() function and the items() method. For example, let's sort the prices dictionary by key:

sorted_prices = dict(sorted(prices.items()))
print(sorted_prices) # Output: {'apple': 1.99, 'banana': 0.99, 'grape': 2.99, 'kiwi': 1.79, 'pear': 2.49}

To sort the dictionary by value, we can pass a lambda function to the sorted() function:

sorted_prices = dict(sorted(prices.items(), key=lambda item: item[1]))
print(sorted_prices) # Output: {'banana': 0.99, 'kiwi': 1.79, 'apple': 1.99, 'pear': 2.49, 'grape': 2.99}

Copying a dictionary

To make a copy of a dictionary, we can use the copy() method or the built-in dict() function. For example, let's make a copy of the prices dictionary:

prices_copy = prices.copy()
print(prices_copy) # Output: {'apple': 1.99, 'banana': 0.99, 'pear': 2.49, 'grape': 2.99, 'kiwi': 1.79}

Alternatively, we can use the dict() function to create a new dictionary with the same key-value pairs:

prices_copy = dict(prices)
print(prices_copy) # Output: {'apple': 1.99, 'banana': 0.99, 'pear': 2.49, 'grape': 2.99, 'kiwi': 1.79}

Clearing a dictionary

To remove all key-value pairs from a dictionary, we can use the clear() method. For example, let's clear the prices dictionary:

prices.clear()
print(prices) # Output: {}

Conclusion

In this blog post, we discussed the top 10 Python dictionary operations, including creating, accessing, modifying, iterating, sorting, copying, and clearing dictionaries. By mastering these operations, you will be able to work efficiently with Python dictionaries and write more effective Python code.

I hope you enjoyed reading our blog post. Stay tuned for more exciting posts on Python.