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 alist - 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
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 alist - 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.
I am trying to understand this code. I understand that first for loop is iterating over the comments using the message column. However, why is a second for loop required and what do the curly braces do?
for comment in comments[' Message']:
s = sentiment.polarity_scores(comment)
for k in sorted(s):
print('{0}: {1}, '.format(k,s[k]))
print(comment)What do [] brackets in a for loop in python mean? - Stack Overflow
python - What is the meaning of a for loop in curly braces? - Stack Overflow
How does python know where the end of a for-loop code block is? There's no indication of when execution should restart.
Is it true that I can't use curly braces in Python? - Stack Overflow
Videos
The "brackets" in your example constructs a new list from an old one, this is called list comprehension.
The basic idea with [f(x) for x in xs if condition] is:
def list_comprehension(xs):
result = []
for x in xs:
if condition:
result.append(f(x))
return result
The f(x) can be any expression, containing x or not.
That's a list comprehension, a neat way of creating lists with certain conditions on the fly.
You can make it a short form of this:
a = []
for record in records.split("\n"):
if record.strip() != '':
a.append(record)
for record in a:
# do something
You can try to add support for braces using a future import statement, but it's not yet supported, so you'll get a syntax error:
>>> from __future__ import braces
File "<stdin>", line 1
SyntaxError: not a chance
Correct for code blocks. However, you do define dictionaries in Python using curly braces:
a_dict = {
'key': 'value',
}
No, there's no alternative to correct indentation. It's a fundamental part of the language.
I have so much problem with indentations...
Perhaps you could benefit from a better editor. A good code editor or IDE will auto-indent code for you. Avoid using something like Notepad which always starts new lines at column 1. The bare minimum you need is an editor that will start new lines at the same indentation level as the previous line.
...as for long codes it makes the code less readable.
I don't see how that can be true. Bad indentation is one of the most pervasive problems I see with new coders' code. It makes code super hard to read. It's like having poor punctuation or capitalization in English. Indentation is a basic readability tool.
Can we use curly brackets?
It scares me a little that you want to forego good indentation and use curly braces instead. Even if curly braces were allowed, you should still indent your code properly. Don't you find this
if (foo) {
while (bar != baz) {
quux();
}
}
easier to read than this?
if (foo) {
while (bar != baz) {
quux(); }
}
And if you already indent your code as a matter of habit the curly braces are redundant. That's what led Python's designers to remove them.
if foo:
while bar != baz:
quux()
I am afraid not. But you can use IDE such as JetBrains which makes it easier to have proper indendation.