-1

I have one dictionary, like the following:

adict = {'1': alist, '0': blist, '2': clist}

I want to perform some things, for all lists in adict except the list with the key '0'.

So I have tried:

for key in adict:
    if key is not '0':
        do something

but the test doesnot work, something is done in all cases, including the one that key=='0'.

I cannot figure out, what is wrong, any help?

Eleftheria
  • 143
  • 2
  • 7
  • 2
    This code executes just fine for me, and goes into "do something" only for `alist` and `clist`. Are you sure you're not loosing something in the translation to a simple example for us? – Jeff Jul 09 '16 at 16:11
  • Modified code (do something as print and some dummy lists for real) works. In any case, you will want to check for value condition via `!=`or `==` paired with a continue. As @JeffL. suggests, please update question with less "edited" code that also o your system produces the error. Thanks. – Dilettant Jul 09 '16 at 16:17

1 Answers1

6

is test for object equality, not value equality. So you're look here if the key is the exact same string object as the literal '0' you type next, not whether the string has the same value. You should probably test for non-equal values like

if key != '0':
    <do something>
Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
  • This is correct and people should be careful with `is` and `==`, but in Python 2.7 the way he did it should evaluate the way he expects. That is, `'0' == '0'` and `'0' is '0'` are both true. I'm wondering if he's mixing dtypes maybe. – Jeff Jul 09 '16 at 16:10
  • @JeffL. yeah, I was surprised that OP reported that this didn't work for `'0'`, so perhaps there's something even deeper going on too – Eric Renouf Jul 09 '16 at 16:11