I have a dict test declared:
test = {'test1': 1, 'test2': 2, 'test3': 3}
And I want to make a copy of test filtering out specific keys that may or may not exist.
I tried the following:
test_copy = {k: test[k] for k not in ('test3', 'test4')}
However Python does not seem to like for not in loops. Is there any way to do this nicely in one line?
I do not believe this question is a duplicate of List comprehension with if statement because I was searching for more than a few minutes specifically for dicts.
The dictionary comprehension test_copy = {k: test[k] for k in test if k not in EXCLUDED_KEYS} will accomplish the copying.
You need to state the "not in" in the conditional:
test_copy = {k: test[k] for k in test if k not in ('test3', 'test4')}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With