In Python How Does "if-else And For" In A Dictionary Comprehension Work
Solution 1:
You are confused by the ... if ... else ...
conditional expression. It is not part of the loop, it is part of the expression generating the value for each key-value pair.
A dictionary comprehension consists of at least one loop, with optionally more loops and if
filters on the right-hand side, and two expressions on the left. One expression to produce a key, and another to produce a value. Together the two expressions make a key-value pair for the resulting dictionary:
{key_expression: value_expression for target in iterable}
The conditional expression simply produces a value based on a test. Either the test evaluates to true and one value is picked, or the value is false and the other is picked:
true_expression iftestelse false_expression
Only the expression picked is evaluated; if test
ends up as false, the false_expression
is executed and the result is returned, the true_expression
is ignored entirely.
Thus, the dictionary comprehension you are looking at is the equivalent of:
data = {}
for n in graph.by_tag('value'):
key = n.attributes['xid']
value = float(n.content) if n.content else np.nan
data[key] = value
So the value
is either set to float(n.content)
, or to np.nan
, depending on the value of n.content
(truethy or not).
Solution 2:
Does a translation help?
data = {}
for n in graph.by_tag('value'):
if n.content:
data[n.attributes['xid']] = float(n.content)
else:
data[n.attributes['xid']] = np.nan
Post a Comment for "In Python How Does "if-else And For" In A Dictionary Comprehension Work"