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:
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)
Syntax of Inline if-else in Python To write an Inline if-else statement we have to follow this syntax. In this syntax, <expression1> will be returned or executed if the condition is true, or else <expression2> will be returned or executed, and these conditions are always executed from left to right.
It is commonly referred to as the conditional operator, inline if (iif), or ternary if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c . One can read it aloud as "if a then b otherwise c".
Example: Python if Statement # If the number is positive, we print an appropriate message num = 3 if num > 0: print(num, "is a positive number.") print("This is always printed.") num = -1 if num > 0: print(num, "is a positive number.") print("This is also always printed.")
To print multiple expressions to the same line, you can end the print statement in Python 2 with a comma ( , ). You can set the end argument to a whitespace character string to print to the same line in Python 3. With Python 3, you do have the added flexibility of changing the end argument to print on the same line.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With