Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 407
Dominique McDonnell Avatar asked Aug 06 '15 03:08

Dominique McDonnell


People also ask

What does this {} mean in Python?

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.

What is the use of curly braces and square braces in Python?

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.

Can we use {} in Python?

In fact, Python supports curly braces, BEGIN/END, and almost any other language's block schemes: see python.org/doc/humor/…!

What is a list with curly brackets in Python?

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.


1 Answers

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
like image 180
Paul Avatar answered Sep 20 '22 20:09

Paul