What is this python expression containing curly braces and a for in loop?

That's a dict comprehension.

It is just like a list comprehension

 [3*x for x in range(5)]
 --> [0,3,6,9,12]

except:

{x:(3*x) for x in range(5)}
---> { 0:0, 1:3, 2:6, 3:9, 4:12 }
  • produces a Python dictionary, not a list
  • uses curly braces {} not square braces []
  • defines key:value pairs based on the iteration through a list

In your case the keys are coming from the Code property of each element and the value is always set to empty array []

The code you posted:

order.messages = {c.Code:[] for c in child_orders}

is equivalent to this code:

order.messages = {}
for c in child_orders:
    order.messages[c.Code] = []

See also:

  • PEP0274
  • Python Dictionary Comprehension

It's dictionary comprehension!

It's iterating through child_orders and creating a dictionary where the key is c.Code and the value is [].

More info here.

Tags:

Python