简体   繁体   中英

Create dictionary from list python

I have many lists in this format:

['1', 'O1', '', '', '', '0.0000', '0.0000', '', '']
['2', 'AP', '', '', '', '35.0000', '105.0000', '', '']
['3', 'EU', '', '', '', '47.0000', '8.0000', '', '']

I need to create a dictionary with key as the first element in the list and value as the entire list. None of the keys are repeating. What is the best way to do that?

>>> lists = [['1', 'O1', '', '', '', '0.0000', '0.0000', '', ''],
['2', 'AP', '', '', '', '35.0000', '105.0000', '', ''],
['3', 'EU', '', '', '', '47.0000', '8.0000', '', '']]
>>> {x[0]: x for x in lists}
{'1': ['1', 'O1', '', '', '', '0.0000', '0.0000', '', ''], '3': ['3', 'EU', '', '', '', '47.0000', '8.0000', '', ''], '2': ['2', 'AP', '', '', '', '35.0000', '105.0000', '', '']}

put all your lists in another list and do this:

my_dict = {}
for list in lists:
  my_dict[list[0]] = list[:]

This basically gets the first element and puts it as a key in my_dict and put the list as the value.

If your indexes are sequential integers, you may use a list instead of a dict:

lst = [None]+[x[1:] for x in sorted(lists)]

use it only if it really fits your problem, though.

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