2

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.

3
  • Hmm, I closed this, but in retrospect it might not be the correct duplicate to close it against... Commented Nov 5, 2015 at 0:16
  • this one? stackoverflow.com/a/1747827/2187558 Commented Nov 5, 2015 at 0:23
  • I am relatively new to python but have experience with other languages. I feel like my question is specific to my particular problem rather than the umbrella questions other people had that might not come up in searches.
    – Mocking
    Commented Nov 5, 2015 at 0:25

2 Answers 2

6

The dictionary comprehension test_copy = {k: test[k] for k in test if k not in EXCLUDED_KEYS} will accomplish the copying.

1
  • Thank you! I tried almost the same thing without the 'in test'.
    – Mocking
    Commented Nov 5, 2015 at 0:15
4

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')}

Not the answer you're looking for? Browse other questions tagged or ask your own question.