How to print using inline if?

This dictionary corresponds to 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:

  • Marked Nodes: 0 1 2 6 7

  • Unmarked nodes: 3 4 5 8 9

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) 
+7
python dynamic printing inline
source share
3 answers

You can use lists:

 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 
+9
source share

Here's another solution that works with python versions that do not yet support the decompression syntax used in the top answer. 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 
+3
source share

We can avoid repeated iteration over the 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)) 
0
source share

All Articles