Warm tip: This article is reproduced from serverfault.com, please click

Create a dictionary from a list of lists with certain criteria

发布于 2020-11-27 20:55:15

I have a list of lists as follows:

l1=[['a1','a2','a3'],['b1','b2'],['c1','a1']]

I want a list of dictionaries as follows:

[{"start":"a1","end":"ä2"},
 {"start":"a2","end":"a3"},
 {"start":"a3","end":"a1"},
 {"start":"b1","end":"b2"},
 {"start":"c1","end":"a1"}
]

I have tried the following code and got index out of bounds exception:

for val in list_listedges:
    for i in range(0,len(val)):
        dict_edges["start"]=val[i]
        dict_edges["end"]=val[i+1]

I am looking for a working solution or enhancement of the above code which would yield the same result.Also, 3 is not a fixed number.It could be 4 or 5 also.In that case,I need all the elements to pair up with each other

Questioner
Sam
Viewed
0
martineau 2020-11-28 14:50:37

You can completely avoid indexing by using the itertools.combinations() function to generate all the possible pairings of the points in each sublist as illustrated below:

from itertools import combinations


l1 = [['a1','a2','a3'], ['b1','b2'], ['c1','a1']]

dicts = [{'start': start, 'end': end}
            for points in l1
                for start, end in combinations(points, 2)]

from pprint import pprint
pprint(dicts, sort_dicts=False)

Output:

[{'start': 'a1', 'end': 'a2'},
 {'start': 'a1', 'end': 'a3'},
 {'start': 'a2', 'end': 'a3'},
 {'start': 'b1', 'end': 'b2'},
 {'start': 'c1', 'end': 'a1'}]