pythonmethodsdictionary

Remove key from dictionary in Python returning new dictionary


I have a dictionary

d = {'a':1, 'b':2, 'c':3}

I need to remove a key, say c and return the dictionary without that key in one function call

{'a':1, 'b':2}

d.pop('c') will return the key value - 3 - instead of the dictionary.

I am going to need one function solution if it exists, as this will go into comprehensions


Solution

  • How about this:

    {i:d[i] for i in d if i!='c'}
    

    It's called Dictionary Comprehensions and it's available since Python 2.7.

    or if you are using Python older than 2.7:

    dict((i,d[i]) for i in d if i!='c')