Create dictionary from list python

2020-07-09 09:59发布

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?

3条回答
Melony?
2楼-- · 2020-07-09 10:34

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.

查看更多
太酷不给撩
3楼-- · 2020-07-09 10:36
>>> 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', '', '']}
查看更多
甜甜的少女心
4楼-- · 2020-07-09 10:47

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.

查看更多
登录 后发表回答