0

I am trying to print a dictionary, but avoid one of the key:value pair, the code is,

[(key,value) for key, value in row.items() if key is not 'key1']

but 'key1' still got printed, how to fix it?

daiyue
  • 7,196
  • 25
  • 82
  • 149
  • 1
    You want `!=`, not `is`. You are testing for value equality, not if the key is the exact same object. – Martijn Pieters May 18 '16 at 11:36
  • @MartijnPieters if I tried `[key for key, value in row.items() if key is not 'key1']`, it can actually print all other keys without 'key1' – daiyue May 18 '16 at 11:47
  • 1
    Only if you added that key *in the same function or both lines of code are at module scope*. You are getting confused by an implementation detail, where some string literals result in reuse of the same object. Use `!=` **always** when comparing values, unless you know absolutely certain that you want to test the same object. – Martijn Pieters May 18 '16 at 11:50

0 Answers0