Reputation: 7832
I have a list of lists with a very specific structure, it looks like the following:
lol = [['geo','DS_11',45.3,90.1,10.2],['geo','DS_12',5.3,0.1,0.2],['mao','DS_14',12.3,90.1,1],...]
I'd like to transform this lol (list of lists) into a dictionary of the following form (note that the second element of each list in the lol is supposed to be unique, thus a good key for my dict:
dict_lol = {'DS_11': ['geo','DS_11',45.3,90.1,10.2], 'DS_12':['geo','DS_12',5.3,0.1,0.2], 'DS_14':['mao','DS_14',12.3,90.1,1],...}
I could do a for loop but i was looking for a more elegant pythonic way to do it.
Thanks!
Upvotes: 6
Views: 97
Reputation: 137320
This is the most Pythonic solution, I believe, using dictionary comprehensions:
dict_lol = {item[1]: item for item in lol}
In case it is not available (eg. in Python <2.7), you can use the following solution:
dict_lol = dict((item[1], item) for item in lol)
Upvotes: 5
Reputation: 16039
Use a dictionary comprehension, available in python 2.7+
In [93]: {x[1]:x for x in lol}
Out[93]:
{'DS_11': ['geo', 'DS_11', 45.3, 90.1, 10.2],
'DS_12': ['geo', 'DS_12', 5.3, 0.1, 0.2],
'DS_14': ['mao', 'DS_14', 12.3, 90.1, 1]}
Upvotes: 6