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.

Community
  • 1
  • 1
Mocking
  • 1,764
  • 2
  • 20
  • 36
  • Hmm, I closed this, but in retrospect it might not be the correct duplicate to close it against... – Andy Hayden Nov 05 '15 at 00:16
  • this one? http://stackoverflow.com/a/1747827/2187558 – LUIS PEREIRA Nov 05 '15 at 00: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 Nov 05 '15 at 00:25

2 Answers2

6

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

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
pppery
  • 3,731
  • 22
  • 33
  • 46
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')}
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535