Reputation: 176
Say I have a dictionary like this :
d = {'ben' : 10, 'kim' : 20, 'bob' : 9}
Is there a way to remove a pair like ('bob',9)
from the dictionary?
I already know about d.pop('bob')
but that will remove the pair even if the value was something other than 9
.
Right now the only way I can think of is something like this :
if (d.get('bob', None) == 9):
d.pop('bob')
but is there an easier way? possibly not using if at all
Upvotes: 4
Views: 6556
Reputation: 212
You want to perform two operations here
1) You want to test the condition d['bob']==9. 2) You want to remove the key along with value if the 1st answer is true.
So we can not omit the testing part, which requires use of if, altogether. But we can certainly do it in one line.
d.pop('bob') if d.get('bob')==9 else None
Upvotes: 1
Reputation: 81594
pop
also returns the value, so performance-wise (as neglectable as it may be) and readability-wise it might be better to use del
.
Other than that I don't think there's something easier/better you can do.
from timeit import Timer
def _del():
d = {'a': 1}
del d['a']
def _pop():
d = {'a': 1}
d.pop('a')
print(min(Timer(_del).repeat(5000, 5000)))
# 0.0005624240000000613
print(min(Timer(_pop).repeat(5000, 5000)))
# 0.0007729860000003086
Upvotes: 9