Not only del easier to understand, but it looks a bit faster than pop () :
$ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}" "for k in d.keys():" " if k.startswith('f'):" " del d[k]" 1000000 loops, best of 3: 0.733 usec per loop $ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}" "for k in d.keys():" " if k.startswith('f'):" " d.pop(k)" 1000000 loops, best of 3: 0.742 usec per loop
Edit: thanks to Alex Martelli for providing instructions on how to do this. I hope I havenβt gone anywhere.
First measure the time it takes to copy:
$ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}" "d1 = d.copy()" 1000000 loops, best of 3: 0.278 usec per loop
Check parameter for copied dict:
$ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}" "d1 = d.copy()" "for k in d1.keys():" " if k.startswith('f'):" " del d1[k]" 100000 loops, best of 3: 1.95 usec per loop $ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}" "d1 = d.copy()" "for k in d1.keys():" " if k.startswith('f'):" " d1.pop(k)" 100000 loops, best of 3: 2.15 usec per loop
Subtracting the cost of copying, we get 1.872 usec for pop() and 1.672 for del .
bernie
source share