Python delete dictionary item while iterating
View Discussion Show
Improve Article Save Article View Discussion Improve Article Save Article A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple.
Let’s see how to delete items from a dictionary while iterating over it. Method 1: Using del() methodPython3
Output: {1: 'Geeks', 3: 'Geeks'} The above code works fine for Python2, (as in that version dictionary keys were unordered). But if we run it with Python3, it throws the following error: for key in myDict.keys(): RuntimeError: dictionary changed size during iteration This runtime error says changing the size of the dictionary during iteration is not allowed (but it is possible). Now, let’s see all the different ways we can delete items from the dictionary while iterating. Method 2: Creating a List of Keys to deleteHere we use a list comprehension to build a list of all the keys that need to be deleted and then iterate through each key in that list deleting them: Python3
Output: {1: 'Geeks', 2: 'For'} Or if you’re new to list comprehensions: We can build up the list of keys to delete using a for loop for that do create a list delete and add keys of all the values we want to delete. Python
Method 3: Using list(myDict)Python3
Output: {1: 'Geeks', 3: 'Geeks'} For Python 3+:
The other answers work fine with Python 2 but raise a
This happens because For Python 2: A simple test in the console shows you cannot modify a dictionary while iterating over it:
As stated in delnan's answer, deleting entries causes problems when the iterator tries to move onto the next entry. Instead, use the
If you need to delete based on the items value, use the
How do you delete something from the dictionary while iterating?First, you need to convert the dictionary keys to a list using the list(dict. keys()) method. During each iteration, you can check if the value of a key is equal to the desired value. If it is True , you can issue the del statement to delete the key.
How do I remove an item from a dictionary python?The clear() method. The clear() method helps clear all the items in the dictionary. Example.. The pop() method. The pop method uses the keyword from the given dictionary to remove an item from that dictionary. ... . The popitem() method. The popitem() method is used to remove the last item added to the dictionary.. How does Del operation work on dictionaries?In a dictionary, Python del can be used to delete a specific key-value pair. For deleting a specific data element in the dictionary, the del statement only accepts the key as an index value.
Which method should you use if you want to delete an item from a dictionary?Use del if you want to delete an item from a dictionary.
|