Skip to content
Advertisement

Representing a creation of list and dictionary using comprehensions in python

I have some questions related to the program I wrote. The data I have is following

data = ['Sectors', 'Countries', 'Regions', 6, 9, 4, 2, 3, 0]
columns = {'countries': 'Countries', 'regions': 'Regions', 'sectors': 'Sectors'}
column_size = 3

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

Output: {'Sectors': [6, 2], 'Countries': [9, 3], 'Regions': [4, 0]}

The following is my code

def converting_to_two_dimensional_list(data: list, column_size: int):
    list_two_dimensional = []
    for l in range(0, len(data), column_size):
        buffer = []
        for j in range(l, l+column_size):
            buffer.append(data[j])
        list_two_dimensional.append(buffer)
    return list_two_dimensional

def final_result(list_two_dimensional: list):
    final_output = {}
    for c in list_two_dimensional[0]:
        buffer = []
        for d in range(len(list_two_dimensional[1:])):
            buffer.append(list_two_dimensional[1:][d][list_two_dimensional[0].index(c)])
        final_output.update({c:buffer})
    return final_output

if __name__ == '__main__':
    result = final_result(converting_to_two_dimensional_list(data, column_size))
    print(result)

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

data = ['Sectors', 'Countries', 'Regions', 6, 9, 4, 2, 3, 0]
column_size = 3
d = data[column_size:]

output = dict(zip(data[0:column_size], [[d[j] for j in range(i, len(d), column_size)] for i in range(column_size)]))

print(output) #{'Sectors': [6, 2], 'Countries': [9, 3], 'Regions': [4, 0]}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement