How to delete a larger number of dictionary items that are not in a list? For example, there is a dictionary dct
and a list `lst:
dct = {'a' : 2, 'b' : 4, 'c' : 6, 'd' : 7}
lst = ['a', 'c']
What would be the most efficient way to filter out the dictionary so that it results in:
dct.items()
Output:
dict_items([('a', 2), ('c', 6)])
Thanks!
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):You could also do this with a dictionary comprehension, along the lines of:
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:
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: