I have some questions related to the program I wrote. The data I have is following
JavaScript
x
4
1
data = ['Sectors', 'Countries', 'Regions', 6, 9, 4, 2, 3, 0]
2
columns = {'countries': 'Countries', 'regions': 'Regions', 'sectors': 'Sectors'}
3
column_size = 3
4
To convert into a specific dictionary based on the number of columns provided, I use the strategy to write 2 functions. The first function is converting into a 2-dimensional list where 1st item of the 2d list provides the column names while other items representing values. The second function gives the expected output by mapping the key and values based on the position where it is situated
JavaScript
1
2
1
Output: {'Sectors': [6, 2], 'Countries': [9, 3], 'Regions': [4, 0]}
2
The following is my code
JavaScript
1
22
22
1
def converting_to_two_dimensional_list(data: list, column_size: int):
2
list_two_dimensional = []
3
for l in range(0, len(data), column_size):
4
buffer = []
5
for j in range(l, l+column_size):
6
buffer.append(data[j])
7
list_two_dimensional.append(buffer)
8
return list_two_dimensional
9
10
def final_result(list_two_dimensional: list):
11
final_output = {}
12
for c in list_two_dimensional[0]:
13
buffer = []
14
for d in range(len(list_two_dimensional[1:])):
15
buffer.append(list_two_dimensional[1:][d][list_two_dimensional[0].index(c)])
16
final_output.update({c:buffer})
17
return final_output
18
19
if __name__ == '__main__':
20
result = final_result(converting_to_two_dimensional_list(data, column_size))
21
print(result)
22
Although I got the expected output, is there any way to represent those functions using comprehension, and if no then , is there any optimized way to get the same output?
Thanks
Advertisement
Answer
you can use list comprehension
JavaScript
1
8
1
data = ['Sectors', 'Countries', 'Regions', 6, 9, 4, 2, 3, 0]
2
column_size = 3
3
d = data[column_size:]
4
5
output = dict(zip(data[0:column_size], [[d[j] for j in range(i, len(d), column_size)] for i in range(column_size)]))
6
7
print(output) #{'Sectors': [6, 2], 'Countries': [9, 3], 'Regions': [4, 0]}
8