15

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?

0

4 Answers 4

29

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:

Sign up to request clarification or add additional context in comments.

Comments

12

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.

Comments

2

Just like list comprehension in Python, it's called dictionary comprehension.

sample_list = [2,4,6,8,9,10] dict = {val: val**2 for val in sample_list if val**2 % 2 == 0} print(dict) //Output: {8: 64, 2: 4, 4: 16, 10: 100, 6: 36} 

The code snippet above maps the numbers to their squares that are even numbers.

Comments

0

Just in addition, and since the question's title is very general: some people ending here might also be looking for the set comprehension as it also contains curly braces and a for loop. So a set comprehension would look like

order.messages = {c.Code for c in child_orders} 

and it will return a Python set. In contrast to the former dictionary comprehension which will return a dictionary:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.