TheRealFakeNews
TheRealFakeNews

Reputation: 8153

How to add a value from a dict to a list only if the dict has a specific key?

Say I have a class Node, with attributes left, right, val. Then suppose we have internal and leaf, where leaf has None for left and right. Then iterating through my_list = [internal, leaf], I only want to add the child nodes to an array only if they exist, so I would do something like

[x.left if x.left is not None for x in my_list]

Is something like this possible? When I try this I get a invalid syntax error

Upvotes: 1

Views: 33

Answers (1)

BrokenBenchmark
BrokenBenchmark

Reputation: 19242

You're almost there! You need to switch the ordering of the for and if clauses:

[x.left for x in my_list if x.left is not None]

Upvotes: 1

Related Questions