2

I tried a few searches but I didn't really know how to ask. I understand short form for loops but this portion within a dictionary is confusing me.

resistances = {k: v if random.random() > self.mutProb else
    not v for k, v in self.resistances.items()}

Is it setting k as the key initially and then cycling through it later on? I'm having difficulty imagining what the 'long hand' would be.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Loz
  • 21
  • 1
  • 3
  • This is called a dictionary comprehension, or dict-comp for short. It follows the same conceptual ideas behind a list-comp. Check [this](http://stackoverflow.com/q/3766711/198633) out – inspectorG4dget Dec 07 '16 at 18:10

1 Answers1

2

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343