1
candidates = ['abacus', 'ball', 'car']

for candidate in candidates:
     if dict[candidate] == "true":
        """next"""
     else:
       continue
"""do something"""

What I'm trying to do here is check for the presence of a term in a dictionary, and if it exists, move the control flow to the next item in the list candidates. I'm having trouble using next(). How do I go about this?

3
  • 1
    what do you mean by next? what do you want to happen if it exists? Going to the next candidate is what continue would do. Commented Apr 24, 2017 at 16:23
  • continue would already move to the next element in an iteration, wouldn't it? what are you trying to do differently between the if and else clauses? Commented Apr 24, 2017 at 16:24
  • 1
    Are you searching for continue ? Commented Apr 24, 2017 at 16:24

3 Answers 3

2

If you want to move the control to the next element in the list if the term exists in the dictionary, you can use continue.

The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.

for candidate in candidates:
    if dict.get(candidate) == "true":
        continue
    else:
        """do something"""

Also, if you use dict[candidate], then if the key does not exist in the dictionary, it gives KeyError. Hence, to avoid the error the better way to check if an element exists in a dictionary is to use get function.

dict.get(candidate) == "true"
Sign up to request clarification or add additional context in comments.

2 Comments

So in this case, if the condition returns "true", the next candidate is examined for this condition and if it fails control moves to the else statement? I thought I had implemented this exact thing to no avail earlier, but will try again
Yeah, you are right. I think that's what you wanted to do. If the condition is true, the continue will stop the further execution in the current iteration and otherwise it will go to the else part.
1

Note, dict is reserved word, so use a different name to avoid problems

candidates = ['abacus', 'ball', 'car']
my_dictionary = {}

for candidate in candidates:
     if candidate not in my_dictionary:
        """do something"""
        break  # exit the loop

Comments

0

Basically you want to go to the next iteration of the list if the current list value is in a dictionary? If so, replace """next""" with pass (no quotation marks).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.