Python provides various data structures to store information. Dictionary is one such python data structure that allows you to store different data types in one place. It also provides rapid lookups increasing access speeds since it consists of key-value pairs. Sometimes you may need to delete dictionary key while iterating python dictionary. There are several ways to do this. We will look at each of these methods one by one.
Python Delete Dictionary Key While Iterating
Here are the different ways to delete dictionary key while iterating.
1. Using del function
In this example, we will iterate through dictionary key and use del function to delete the desired item.
>>> d={1:'a',2:'b',3:'c'} >>> for i in d.keys(): if i==2: del d[2] >>> d {1: 'a', 3: 'c'}
Similarly, we can also delete items using values, during iteration.
>>> d={1:'a',2:'b',3:'c'} >>> for i in d.keys(): if d[i]=='b': del d[i] >>> d {1: 'a', 3: 'c'}
Please note, the del function works only in Python 2 and not in Python 3. For python 3, you can use the following methods.
2. Using dictionary comprehension
Dictionary comprehensions are similar to list comprehensions. They can also be used to exclude keys as per our requirement.
Here is an example.
>>> d={1:'a',2:'b',3:'c'} >>> for key in [key for key in d if key == 3]: del d[key] >>> d {1: 'a', 2: 'b'}
3. Using List of Keys
You can also iterate through list of keys and delete required item.
>>> d={1:'a',2:'b',3:'c'} >>> for i in list(d): if i==2: del d[i] >>> d {1: 'a', 3: 'c'}
In this article, we have seen a few ways to delete dictionary items while iterating through it.
Also read:
Python Remove Item from List During Iteration
How to Rename File Using Python
How to Uninstall Java in Ubuntu
How to Format USB Drives in Linux
How to Convert Epoch to Date in Linux
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.