Skip to content

Instantly share code, notes, and snippets.

@innat
Last active Nov 24, 2018
Embed
What would you like to do?
Removing Key from Python Dictionary.

We can delete a key from a Python dictionary by the some following approaches.

Using the del keyword; it's almost the same approach like you did though -

     myDict = {'one': 100, 'two': 200, 'three': 300 }
     print(myDict)  # {'one': 100, 'two': 200, 'three': 300}
     if myDict.get('one') : del myDict['one']
     print(myDict)  # {'two': 200, 'three': 300}

Or

We can do like following:

But one should keep in mind that, in this process actually it won't delete any key from the dictionary rather than making specific key excluded from that dictionary. In addition, I observed that it returned a dictionary which was not ordered the same as myDict.

    myDict = {'one': 100, 'two': 200, 'three': 300, 'four': 400, 'five': 500}
    {key:value for key, value in myDict.items() if key != 'one'}

If we run it in the shell, it'll execute something like {'five': 500, 'four': 400, 'three': 300, 'two': 200} - notice that it's not the same ordered as myDict. Again if we try to print myDict, then we can see all keys including which we excluded from the dictionary by this approach. However, we can make a new dictionary by assigning the following statement into a variable:

    var = {key:value for key, value in myDict.items() if key != 'one'}

Now if we try to print it, then it'll follow the parent order:

    print(var) # {'two': 200, 'three': 300, 'four': 400, 'five': 500}

Or

Using the pop() method.

    myDict = {'one': 100, 'two': 200, 'three': 300}
    print(myDict)

    if myDict.get('one') : myDict.pop('one')
    print(myDict)  # {'two': 200, 'three': 300}

The difference between del and pop is that, using pop() method, we can actually store the key's value if needed, like the following:

    myDict = {'one': 100, 'two': 200, 'three': 300}
    if myDict.get('one') : var = myDict.pop('one')
    print(myDict) # {'two': 200, 'three': 300}
    print(var)    # 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment