Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading