In this Python Dictionary article we want to talk about Manipulation in Python Dictionary, so Python dictionaries are powerful and widely used data structure in. they allows you for efficient storage and retrieval of data using key value pairs. also dictionaries are not just for storage and retrieval, they can also be manipulated in different ways to suit different use cases.
In this article we want to explore some common techniques for manipulating Python dictionaries, including adding and removing key value pairs, updating values and sorting.
Python Dictionary Manipulation
First let’s talk about adding new key value pairs to dictionary. you can simply assign a value to a new key as follows.
1 2 3 |
my_dict = {"apple": 1, "banana": 2} my_dict["geekscoders.com"] = 3 print(my_dict) |
This will be the result
Removing key value pairs is also simple using the del keyword.
1 2 3 4 5 |
my_dict = {"apple": 1, "banana": 2} my_dict["geekscoders.com"] = 3 print(my_dict) del my_dict["apple"] print(my_dict) |
This will be the result
You can also use pop() method to remove a key-value pair while simultaneously returning the value.
1 2 3 |
value = my_dict.pop("banana") print(my_dict) print(value) |
Updating values in dictionary is also straightforward. you can simply re assign new value to an existing key as follows.
1 2 |
my_dict["orange"] = 4 print(my_dict) |
You can also use update() method to update multiple values at once using another dictionary.
1 2 3 4 |
my_dict = {"apple": 1, "banana": 2} new_dict = {"orange": 3, "pear":4} my_dict.update(new_dict) print(my_dict) |
This will be the result
Sorting a dictionary by its keys or values can be useful in many situations. to sort a dictionary by keys, you can use sorted() function:
1 2 3 |
my_dict = {"c": 1, "a": 2, "b": 3} sorted_dict = {k: my_dict[k] for k in sorted(my_dict)} print(sorted_dict) |
For sorting a dictionary by values, you can use the sorted() function with key argument.
1 2 3 |
my_dict = {"c": 1, "a": 2, "b": 3} sorted_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1])} print(sorted_dict) |