Remove key from dictionary in Python returning new dictionary

If you need an expression that does this (so you can use it in a lambda or comprehension) then you can use this little hack trick: create a tuple with the dictionary and the popped element, and then get the original item back out of the tuple:

(foo, foo.pop(x))[0]

For example:

ds = [{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}]
[(d, d.pop('c'))[0] for d in ds]
assert ds == [{'a': 1, 'b': 2}, {'a': 4, 'b': 5}]

Note that this actually modifies the original dictionary, so despite being a comprehension, it's not purely functional.


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')

Why not roll your own? This will likely be faster than creating a new one using dictionary comprehensions:

def without(d, key):
    new_d = d.copy()
    new_d.pop(key)
    return new_d

When you invoke pop the original dictionary is modified in place.

You can return that one from your function.

>>> a = {'foo': 1, 'bar': 2}
>>> a.pop('foo')
1
>>> a
{'bar': 2}