Search code examples
pythonlistsortingdictionarydata-analysis

Fastest way to sort sublists in dictionary?


What would be the fastest way to sort sublists elemnts in to dictionary in python? I will give the example how I tackled the problem but I think there should be a better way. It is not a problem for smal lists. But I have a lot of data to sort in that way so I need to have optimized version.

Input:

my_data = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]

my_dict = {}

my_dict['key 0'] = [item[0] for item in my_data]
my_dict['key 1'] = [item[1] for item in my_data]
my_dict['key 2'] = [item[2] for item in my_data]
my_dict['key 3'] = [item[3] for item in my_data]
my_dict['key 4'] = [item[4] for item in my_data]

enter cod`enter code here`e here

And this is what I want to get as output.

Output

{'key 0': [1, 1, 1],
 'key 1': [2, 2, 2],
 'key 2': [3, 3, 3],
 'key 3': [4, 4, 4],
 'key 4': [5, 5, 5]}

Solution

  • my_data = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
    keys = ["key 0", "key 1", "key 2", "key 3", "key 4"]
    
    print({k: [row[index] for row in my_data] for index, k in enumerate(keys)})
    

    EDIT: Probably, the fastest you can get is by using zip and enumerate and not converting the results to a list nor string formatting the keys:

    print(dict(enumerate(zip(*my_data))))  
    # {0: (1, 1, 1), 1: (2, 2, 2), 2: (3, 3, 3), 3: (4, 4, 4), 4: (5, 5, 5)}
    

    If the keys are predefined, just use zip again:

    print(dict(zip(keys, zip(*my_data))))  
    # {'key 0': (1, 1, 1), 'key 1': (2, 2, 2), 'key 2': (3, 3, 3), 'key 3': (4, 4, 4), 'key 4': (5, 5, 5)}