Python delete dictionary item while iterating

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • 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.

    Note: In Python 2 dictionary keys were unordered. As of Python 3, they are ordered.

    Let’s see how to delete items from a dictionary while iterating over it. 

    Method 1: Using del() method

    Python3

    myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

    for key in myDict.keys():

        if key == 2:

            del myDict[key]

    print(myDict)

    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 delete

    Here 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

    myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

    delete = [key for key in myDict if key == 3]

    for key in delete:

        del myDict[key]

    print(myDict)

    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

    myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

    delete = []

    for key in myDict:

        if key == 3:

            delete.append(key)

    for i in delete:

        del myDict[i]

    print(myDict)

    Method 3: Using list(myDict) 

    Python3

    myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

    for key in list(myDict):

        if key == 2:

            del myDict[key]

    print(myDict)

    Output: 

    {1: 'Geeks', 3: 'Geeks'}

    For Python 3+:

    >>> mydict
    {'four': 4, 'three': 3, 'one': 1}
    
    >>> for k in list(mydict.keys()):
    ...     if mydict[k] == 3:
    ...         del mydict[k]
    
    >>> mydict
    {'four': 4, 'one': 1}
    

    The other answers work fine with Python 2 but raise a RuntimeError for Python 3:

    RuntimeError: dictionary changed size during iteration.

    This happens because mydict.keys() returns an iterator not a list. As pointed out in comments simply convert mydict.keys() to a list by list(mydict.keys()) and it should work.


    For Python 2:

    A simple test in the console shows you cannot modify a dictionary while iterating over it:

    >>> mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
    
    >>> for k, v in mydict.iteritems():
    ...    if k == 'two':
    ...        del mydict[k]
    
    ------------------------------------------------------------
    Traceback (most recent call last):
      File "", line 1, in 
    RuntimeError: dictionary changed size during iteration
    

    As stated in delnan's answer, deleting entries causes problems when the iterator tries to move onto the next entry. Instead, use the keys() method to get a list of the keys and work with that:

    >>> for k in mydict.keys():
    ...    if k == 'two':
    ...        del mydict[k]
    
    >>> mydict
    {'four': 4, 'three': 3, 'one': 1}
    

    If you need to delete based on the items value, use the items() method instead:

    >>> for k, v in mydict.items():
    ...     if v == 3:
    ...         del mydict[k]
    
    >>> mydict
    {'four': 4, 'one': 1}
    

    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.