从列表python创建字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16929359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:01:54  来源:igfitidea点击:

Create dictionary from list python

pythonlistdictionary

提问by wannabe_geek

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?

我需要创建一个字典,键作为列表中的第一个元素,值作为整个列表。没有一个键是重复的。最好的方法是什么?

采纳答案by AliBZ

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_dictand put the list as the value.

这基本上获取第一个元素并将其作为键my_dict放入并将列表作为值放入。

回答by jamylak

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

回答by Elazar

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 reallyfits your problem, though.

但是,仅当它确实适合您的问题时才使用它。