[英]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. 我需要创建一个字典,其中key作为列表中的第一个元素,value作为整个列表。 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. 这基本上获取第一个元素并将其作为my_dict
的键,并将列表作为值。
If your indexes are sequential integers, you may use a list instead of a dict: 如果索引是顺序整数,则可以使用列表而不是dict:
lst = [None]+[x[1:] for x in sorted(lists)]
use it only if it really fits your problem, though. 但是,只有当它真的适合你的问题时才使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.