7

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}

3 Answers 3

14

Use the del statement:

x = {'a': 5, 'b': 2, 'c': 3}
del x['a'], x['b']
print x
{'c': 3}
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm
4

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 not in remove_keys}

Here are the results of 1M iterations:

  1. 1.88s 1.9 ns/iter (100%)
  2. 2.41s 2.4 ns/iter (128%)
  3. 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 not in remove_keys}
  1. 2.03s 2.0 ns/iter (100%)
  2. 2.38s 2.4 ns/iter (117%)
  3. 4.11s 4.1 ns/iter (202%)

Still, del is the fastest.

Comments

2

The general form I use is this:

  1. Produce a list of keys to delete from the mapping;
  2. 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'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.