pooperdooper
pooperdooper

Reputation: 155

How to print with inline if statement?

This dictionary corresponds with numbered nodes:

{0: True, 1: True, 2: True, 3: False, 4: False, 5: False, 6: True, 7: True, 8: False, 9: False}

Using two print statements, I want to print marked and unmarked nodes as follows:

I want something close to:

print("Marked nodes: %d" key in markedDict if markedDict[key] = True)
print("Unmarked nodes: %d" key in markedDict if markedDict[key] = False)

Upvotes: 7

Views: 507

Answers (3)

Jayavanth
Jayavanth

Reputation: 1

We can avoid duplicate iteration over dictionary.

marked = []
unmarked = []
mappend = marked.append
unmappend = unmarked.append
[mappend(str(x))if y else unmappend(str(x)) for x, y in d.iteritems()]
print "Marked - %s\r\nUnmarked - %s" %(' '. join(marked), ' '. join(unmarked))

Upvotes: 0

timgeb
timgeb

Reputation: 78650

Here's another solution that works with versions of python which do not support the unpacking syntax used in the top answer yet. Let d be your dictionary:

>>> print('marked nodes: ' + ' '.join(str(x) for x,y in d.items() if y))
marked nodes: 0 1 2 6 7
>>> print('unmarked nodes: ' + ' '.join(str(x) for x,y in d.items() if not y))
unmarked nodes: 3 4 5 8 9

Upvotes: 3

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17132

You can use list comprehensions:

nodes = {0: True, 1: True, 2: True,
         3: False, 4: False, 5: False,
         6: True, 7: True, 8: False, 9: False}

print("Marked nodes: ", *[i for i, value in nodes.items() if value])
print("Unmarked nodes: ", *[i for i, value in nodes.items() if not value])

Output:

Marked nodes:  0 1 2 6 7
Unmarked nodes:  3 4 5 8 9

Upvotes: 9

Related Questions