Python Dictionary Manipulation

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.

 

 

This will be the result

Python Dictionary Manipulation
Python Dictionary Manipulation

 

 

Removing key value pairs is also simple using the del keyword.

 

 

This will be the result

Manipulation in Python Dictionary
Manipulation in Python Dictionary

 

 

You can also use pop() method to remove a key-value pair while simultaneously returning the value.

 

 

Updating values in dictionary is also straightforward. you can simply re assign new value to an existing key as follows.

 

You can also use update() method to update multiple values at once using another dictionary.

 

 

This will be the result

Python Dictionary
Python Dictionary

 

 

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:

 

 

For sorting a dictionary by values, you can use the sorted() function with key argument.

 

 

Learn More on Python Dictionaries 

Leave a Comment