Is it a requirement that you mutate the existing dictionary, or is producing a new, smaller dictionary okay?
If you can produce a new dictionary, the phrasing of your question might direct you to Python's filter function, which would you implement along the lines of (assuming key_list
is the list of key values you want to keep):
new_dict = filter(lambda pair: pair[0] in key_list, old_dict)
You could also do this with a dictionary comprehension, along the lines of:
new_dict = { key : value for (key, value) in old_dict if key in key_list }
If you absolutely, positively must mutate the original dictionary there are ways to do this in a single line in Python but they would not be entirely clear to a Python programmer, so I'd probably do it in a loop:
for key in old_dict:
if key not in key_list:
del old_dict[key]
This works in Python 2 but not Python 3 where the deletion inside the for loop will break the iteration. For Python 3 (I think) you need to do something like:
del_keys = [ key for key in old_dict if key not in key_list ]
for key in del_keys:
del old_dict[key]