The Python Oracle

Removing multiple keys from a dictionary safely

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC M Beethoven - Piano Sonata No 3 in C 3

--

Chapters
00:00 Question
00:38 Accepted answer (Score 78)
00:58 Answer 2 (Score 342)
01:12 Answer 3 (Score 117)
01:41 Answer 4 (Score 23)
02:11 Thank you

--

Full question
https://stackoverflow.com/questions/8995...

Accepted answer links:
[dict.pop()]: https://stackoverflow.com/a/8995774/9483...

Answer 2 links:
[dict.pop]: https://docs.python.org/library/stdtypes...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #dictionary

#avk47



ANSWER 1

Score 371


Using dict.pop:

d = {'some': 'data'}
entries_to_remove = ('any', 'iterable')
for k in entries_to_remove:
    d.pop(k, None)



ANSWER 2

Score 129


Using Dict Comprehensions

final_dict = {key: value for key, value in d.items() if key not in [key1, key2]}

where key1 and key2 are to be removed.

In the example below, keys "b" and "c" are to be removed & it's kept in a keys list.

>>> a
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> keys = ["b", "c"]
>>> print {key: a[key] for key in a if key not in keys}
{'a': 1, 'd': 4}
>>> 



ACCEPTED ANSWER

Score 78


Why not like this:

entries = ('a', 'b', 'c')
the_dict = {'b': 'foo'}

def entries_to_remove(entries, the_dict):
    for key in entries:
        if key in the_dict:
            del the_dict[key]

A more compact version was provided by mattbornski using dict.pop()




ANSWER 4

Score 21


If you also need to retrieve the values for the keys you are removing, this would be a pretty good way to do it:

values_removed = [d.pop(k, None) for k in entities_to_remove]

You could of course still do this just for the removal of the keys from d, but you would be unnecessarily creating the list of values with the list comprehension. It is also a little unclear to use a list comprehension just for the function's side effect.