Reputation: 6497
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
Upvotes: 99
Views: 79355
Reputation: 250
Probably not exactly what you're looking for, but here's a fun one that (ab)uses the maligned walrus operator:
>>> x = {"a": "a", "b": "b"}
>>> (x_without_a := dict(x)).pop("a")
'a'
>>> x
{'a': 'a', 'b': 'b'}
>>> x_without_a
{'b': 'b'}
Upvotes: 1
Reputation: 1017
Here's a one-liner using the built-in filter
function:
>>> d = {'a':1, 'b':2, 'c':3}
>>> dict(filter(lambda x: x[0] != 'c', d.items()))
{'a': 1, 'b': 2}
Upvotes: 1
Reputation: 3337
Dict comprehension seems to be more elegant
{k:v for k,v in d.items() if k != 'c'}
Upvotes: 3
Reputation: 13
solution from me
item = dict({"A": 1, "B": 3, "C": 4})
print(item)
{'A': 1, 'B': 3, 'C': 4}
new_dict = (lambda d: d.pop('C') and d)(item)
print(new_dict)
{'A': 1, 'B': 3}
Upvotes: 1
Reputation: 243
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}
Upvotes: 8
Reputation: 8585
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.
Upvotes: 18
Reputation: 27812
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')
Upvotes: 121
Reputation: 116
this will work,
(lambda dict_,key_:dict_.pop(key_,True) and dict_)({1:1},1)
EDIT this will drop the key if exist in the dictionary and will return the dictionary without the key,value pair
in python there are functions that alter an object in place, and returns a value instead of the altered object, {}.pop function is an example.
we can use a lambda function as in the example, or more generic below (lambda func:obj:(func(obj) and False) or obj) to alter this behavior, and get a the expected behavior.
Upvotes: 0
Reputation: 8497
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
Upvotes: 31