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

I just came across this python line:

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

I have no idea what he is doing, except that he child_orders over the child_orders list and puts the result in order.messages .

What is he doing and what is called?

+4
source share
2 answers

This is an understanding of dictate.

It seems like a list comprehension

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

Besides

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

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

You have sent the code:

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

equivalent to this code:

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

See also:

+8
source

This is an understanding of the dictionary!

It child_orders through child_orders and creates a dictionary, where the key is c.Code and the value is [] .

More details here .

+8
source

All Articles