Remove more than one key from Python dict
Use the del
statement:
x = {'a': 5, 'b': 2, 'c': 3}
del x['a'], x['b']
print x
{'c': 3}
The general form I use is this:
- Produce a list of keys to delete from the mapping;
- Loop over the list and call del for each.
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'}
Remove a number of keys
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 no in remove_keys}
Here are the results of 1M iterations:
- 1.88s 1.9 ns/iter (100%)
- 2.41s 2.4 ns/iter (128%)
- 4.15s 4.2 ns/iter (221%)
So del
is the fastest.
Remove a number of keys safely
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 no in remove_keys}
- 2.03s 2.0 ns/iter (100%)
- 2.38s 2.4 ns/iter (117%)
- 4.11s 4.1 ns/iter (202%)
Still, del
is the fastest.