Reputation: 52143
Is there any efficient shortcut method to delete more than one key at a time from a python dictionary?
For instance;
x = {'a': 5, 'b': 2, 'c': 3}
x.pop('a', 'b')
print x
{'c': 3}
Upvotes: 6
Views: 7528
Reputation: 35374
I have tested the performance of three methods:
d = dict.fromkeys('abcdefghijklmnopqrstuvwxyz')
remove_keys = set('abcdef')
# Method 1
for key in remove_keys:
del d[key]
# Method 2
for key in remove_keys:
d.pop(key)
# Method 3
{key: v for key, v in d.items() if key not in remove_keys}
Here are the results of 1M iterations:
So del
is the fastest.
However, if you want to delete safely, so that it does not fail with KeyError, you have to modify the code:
# Method 1
for key in remove_keys:
if key in d:
del d[key]
# Method 2
for key in remove_keys:
d.pop(key, None)
# Method 3
{key: v for key, v in d.items() if key not in remove_keys}
Still, del
is the fastest.
Upvotes: 3
Reputation:
The general form I use is this:
Example:
Say I want to delete all the string keys in a mapping. Produce a list of them:
>>> x={'a':5,'b':2,'c':3,1:'abc',2:'efg',3:'xyz'}
>>> [k for k in x if type(k) == str]
['a', 'c', 'b']
Now I can delete those:
>>> for key in [k for k in x if type(k) == str]: del x[key]
>>> x
{1: 'abc', 2: 'efg', 3: 'xyz'}
Upvotes: 2
Reputation: 134601
Use the del
statement:
x = {'a': 5, 'b': 2, 'c': 3}
del x['a'], x['b']
print x
{'c': 3}
Upvotes: 14