Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From a list of lists to a dictionary

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!

like image 639
Dnaiel Avatar asked Feb 20 '13 17:02

Dnaiel


1 Answers

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]}
like image 89
mbatchkarov Avatar answered Oct 12 '22 22:10

mbatchkarov