Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a key/value pair in python dictionary?

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

like image 384
FoxyZ Avatar asked Oct 16 '25 18:10

FoxyZ


2 Answers

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
like image 199
DeepSpace Avatar answered Oct 19 '25 08:10

DeepSpace


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

like image 34
MD AZAD HUSSAIN Avatar answered Oct 19 '25 06:10

MD AZAD HUSSAIN