I just came across this line of python:
order.messages = {c.Code:[] for c in child_orders}
I have no idea what it is doing, other than it is looping over the list child_orders
and placing the result in order.messages
.
What does it do and what is it called?
In languages like C curly braces ( {} ) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.
Curly braces create dictionaries or sets. Square brackets create lists. To create an empty set, you can only use set() . Sets are collections of unique elements and you cannot order them.
In fact, Python supports curly braces, BEGIN/END, and almost any other language's block schemes: see python.org/doc/humor/…!
Sets. A set is an is unordered and unindexed collection. In Python, sets are written with curly braces. In addition to being iterable and mutable, a set has no duplicate elements.
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 }
dictionary
, not a list
{}
not square braces []
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With