In the following code snippet:
JavaScript
x
13
13
1
from collections import OrderedDict
2
3
data = [OrderedDict([('sale', '143017'), ('profit', '345'), ('quantity', '45')]),
4
OrderedDict([('sale', '243215'), ('profit', '400'), ('quantity', '105')]),
5
OrderedDict([('sale', '98342'), ('profit', '100'), ('quantity', '55')])]
6
7
sale_list = []
8
for i in range(2):
9
sale_list.append(list(data[i].items())[0][1])
10
11
print(sale_list)
12
13
The output is:
JavaScript
1
2
1
['143017', '243215']
2
I wonder how to change the for loop to a list comprehension?
Advertisement
Answer
JavaScript
1
11
11
1
from collections import OrderedDict
2
3
data = [OrderedDict([('sale', '143017'), ('profit', '345'), ('quantity', '45')]),
4
OrderedDict([('sale', '243215'), ('profit', '400'), ('quantity', '105')]),
5
OrderedDict([('sale', '98342'), ('profit', '100'), ('quantity', '55')])]
6
7
8
sale_list = [ list(data[i].items())[0][1] for i in range(2) ]
9
10
print(sale_list)
11
This should work, here is a basic example
JavaScript
1
7
1
h_letters = []
2
3
for letter in 'human':
4
h_letters.append(letter)
5
6
print(h_letters)
7
Would instead be
JavaScript
1
3
1
h_letters = [ letter for letter in 'human' ]
2
print( h_letters)
3