Search code examples
pythondictionarynested-listsenumerate

Create dictionary from the position of elements in nested lists


I want to create a dictionary using the position of elements in each list of lists. The order of each nested list is very important and must remain the same.

Original nested lists and desired dictionary keys:

L_original = [[1, 1, 3], [2, 3, 8]]
keys = ["POS1", "POS2", "POS3"]

Desired dictionary created from L_original:

L_dictionary = {"POS1": [1, 2], "POS2": [1, 3], "POS3": [3, 8]}

The code I have so far fails the conditionals and ends on the else statement for each iteration.

for i in L_original:
    for key, value in enumerate(i):
        if key == 0:
            L_dictionary[keys[0]] = value
        if key == 1:
            L_dictionary[keys[1]] = value
        if key == 2:
            L_dictionary[keys[2]] = value
        else:
            print(f"Error in positional data processing...{key}: {value} in {i}")

Solution

  • Use a list comprehension as you enumerate

    L_dictionary = dict()
    for i, k in enumerate(keys):
        L_dictionary[k] = [x[i] for x in L_original]
    

    Or simply

    L_dictionary = {k: [x[i] for x in L_original] for i, k in enumerate(keys)}