Home > Software design >  Nested comprehension: list of list to single element dictionary
Nested comprehension: list of list to single element dictionary

Time:08-26

I have a list of list. I am trying to convert it to a dictionary with the key being the n-element of the sublist and the value the first element of the list. I was able to achieve the expected results using loop but I am looking for a more elegant way to write it, using list comprehension for example

array = [
    [1, 2, 3],
    [5, 4, 8]
]

out = {}
for x in array:
    y = x[0]
    z = x[1:]
    for k in z:
        out[k] = y 

Result:

out = {
   2 : 1,
   3 : 1,
   4 : 5,
   8 : 5
}

CodePudding user response:

First, it helps to avoid creating additional variables when writing comprehensions.

Step 1: eliminate the variables:

out = {}
for x in array:
    for k in x[1:]:
        out[k] = x[0]

Step 2: replace the pattern

out = {}
for ...:
    ...
    out[k] = v

by out = {k: v for ...}, where you repeat the for clauses in the same order as they appear in the original code:

out = {k: x[0] for x in array for k in x[1:]}

CodePudding user response:

Did it over two lines to show what I did but this can all be put into one line.

D1 = {l[0]:l[1:] for l in array}

Out = {v[x]:k for k,v in D1.items() for x in range(len(v)) }

All in one line

Out = {v[x]:k for k,v in {l[0]:l[1:] for l in array}.items() for x in range(len(v)) }
  • Related