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