简体   繁体   中英

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!

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

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)

像这样:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM