2013-02-20 69 views
6

我有一个列表的列表具有非常特殊结构的列表,它看起来像如下:从列表来字典

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],...] 

我想这LOL(名单列表)转变成以下形式的字典(注意,在LOL的每个列表的第二个元素应该是唯一的,因此,对于我的字典了良好的关键:

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],...} 

我能为循环做了,但我一直在寻找一种更优雅的pythonic方式去做。

谢谢!

回答

6

使用字典理解,可在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]} 
5

这是最Python化的解决方案,我相信,用dictionary comprehensions

dict_lol = {item[1]: item for item in lol} 

如果它不可用(如:在Python < 2.7)中,可以使用以下解决方案:

dict_lol = dict((item[1], item) for item in lol) 
2

像这样:

{l[1]:l for l in lol}