0

Delete all dict items except for some

Problem
I have given some dict with an arbitrary number of items (for simplicity with two items):

dictionary = {'foo': baz, 'bar': baz}

I want to delete/remove all items, which are not within a defined list of keys.

keys_to_keep = ['foo']

Expected result:

dictionary = {'foo': baz}

However I want to do this without creating a new dict, so I want to modify the original dict.

My Attempts
Simple for loop.

for key in dictionary.keys():
    if key not in keys_to_keep:
        del dictionary[key]

Question
The above mentioned implementation works, but I was wondering if there is a shorter/faster solution to this problem. Maybe something like the example below, but (as I said) without creating a new dict.

dictionary = {key: value for key, value in dictionary.items() if key in keys_to_keep}

Thanks.

References
Related stackoverflow question

ffent
  • 31
  • 2
  • 3
    What's the reason for the constraint of not building a new dict? – blhsing Jun 05 '20 at 15:52
  • 1
    Does this answer your question? [Remove entries of a dictionary that are not in a set](https://stackoverflow.com/questions/9735504/remove-entries-of-a-dictionary-that-are-not-in-a-set). This removes the `if` check which I believe is as short as you can get (in-place...) – Tomerikoo Jun 05 '20 at 15:52
  • Acually the [second answer](https://stackoverflow.com/a/9735595/6045800) does it in one line... – Tomerikoo Jun 05 '20 at 15:59
  • @blhsing I had some issues with the creation of a new dict within the recursion I'm using it. – ffent Jun 05 '20 at 16:05
  • @Tomerikoo Thanks for this reference, but shouldn't you avoid calling "__delitem __"? – ffent Jun 05 '20 at 16:07
  • I don't see a special reason not to... It's basically the functino form of `del` to be able to use inside a `map` – Tomerikoo Jun 05 '20 at 16:11

0 Answers0