You have a dictionary comprehension, and for each iteration of the for
loop, two expressions are executed. One for the key, and one for the value.
So in the expression:
{k: v if random.random() > self.mutProb else not v
for k, v in self.resistances.items()}
both k
and v if random.random() > self.mutProb else not v
are expressions, and the first produces the key, the second the value of each key-value pair for the resulting dictionary.
If you were to use a for
loop, the above would be implemented as:
resistances = {}
for k, v in self.resistances.items():
key = k
value = v if random.random() > self.mutProb else not v
resistances[key] = value
In your example, the key is simply set to the value of the variable k
, but you can use more complex expressions too.
Dictionary comprehensions are a specialisation of Dictionary Displays; the other form produces a dictionary without looping, from a static list of key-value pairs, and is perhaps more familiar to you:
d = {key1: value1, key2: value2}
but the documentation states:
A dict comprehension, in contrast to list and set comprehensions, needs two expressions separated with a colon followed by the usual “for” and “if” clauses. When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced.