skipping a turn of a for-loop using except

2472 views python
1

So I am using a function which adds components to the system via:

es.add(components[i][0] for i in components.keys())

components is a python dictionary, which looks like this:

components = {'a': (a0, a1),
              'b': (b0, None)}

What I am trying the achieve is that I want to run above mentioned for-loop with except, which will be able to not run the add() function if the components dictionary gives None.

What I tried:

es.add(components[i][1] for i in components.keys() except None)

Ofc it gives a syntax error. What is the syntax for it?


EXAMPLE:

es.add(components[i][1] for i in components.keys())

Above is equal with:

es.add(a1)
es.add(None)

I want to write my for-loop in a way it adds only a1 and skips None.

answered question

What do you mean, run it "with expect"? What is expect in this situation?

run add() function if the input of the dictionary is not None.

Maybe he meant except?

you are right, fixed question

1 Answer

3

I assume that it is like [components[i][1] for i in components.keys() if type(components[i][1]) != type(None)]

so that below code can work fine

es.add(components[i][1] for i in components.keys() if type(components[i][1]) != type(None))

posted this

Have an answer?

JD

Please login first before posting an answer.