0

i have a question about the following code

 smaller={}
 for( dest in a[neigbour].keys())

    if(dest in smaller.keys() == False):
        print 'false'
    }

I can't make this code print false.. am I doing something wrong? I wonder if I am doing the correct thing to check the statement dest in smaller.keys() == False

2
  • 2
    You should never compare with False or True in conditional statements. Commented Oct 21, 2012 at 23:44
  • If you're testing membership in a dictionary, you don't need x in d.keys(), you can simply use x in d. Similarly, for x in d: loops over the keys. Commented Oct 21, 2012 at 23:48

3 Answers 3

4

The oppisite of dest in smaller.keys() is dest not in smaller.keys(). No need to compare to False or True:

if (dest not in smaller.keys()):

Documentation for in and not in: http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange

Sign up to request clarification or add additional context in comments.

Comments

4

Your Python syntax is quite confused. For one, you need a : after your for statement, and it's generally not idiomatic to use braces around a for loop in Python. Also, instead of comparing to False with ==, generally we use not:

smaller = {}
for dest in a[neighbour].keys():
    if dest not in smaller.keys():
        print('false')

Comments

1

As well as the other answers you've been given, the code could be written as:

for key in a[neighbour].viewkeys() - smaller.viewkeys():
    print key, 'not found'

Which takes advantage of the set like behaviour of .viewkeys to easily create a set of all keys in a[neighbour] not in b, then loops over that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.