Python:字典列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34191817/
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 14:34:39  来源:igfitidea点击:

Python: List of lists to dictionary

pythonlistdictionary

提问by JustAskingThings

I have a file which contains data in the following format: please note this is an example of what it looks like, the actual file contains more than 2 rows

我有一个包含以下格式数据的文件:请注意这是一个示例,实际文件包含超过 2 行

1    30    5
2    64    4

I read in the file, convert the text to integers, and store them into a list. This is done with the following code:

我读入文件,将文本转换为整数,然后将它们存储到列表中。这是通过以下代码完成的:

file = open("dataFile.txt", "r") 
items = [] 
for line in file:
    line = map(int,line.split()) #convert the text data to integers 
    items.append(line) #add text data to list

The current format for the list looks like:

列表的当前格式如下所示:

[[1, 30, 5], [2, 64, 4]]

I need to turn my list of lists into a dictionary. How would one go about doing this?

我需要将我的列表列表变成字典。怎么做呢?

Dictionary key should be the first element

字典键应该是第一个元素

采纳答案by TessellatingHeckler

I'm going to play guess-what-you-want, and assume the first numbers in each row are in fact some kind of sequential identifier, and you want

我要玩猜你想要什么,并假设每一行中的第一个数字实际上是某种顺序标识符,并且你想要

1    30    5
2    64    4

to become

成为

1  : [30, 5]
2  : [64, 4]

so...

所以...

with open("dataFile.txt") as dataFile:
    items = {}
    for line in dataFile:
        line = map(int, line.split())  #convert the text data to integers
        key, value = line[0], line[1:]
        items[key] = value

(and I've changed the name of filebecause file()is already a builtin function in Python, and reusing that name for something else is bad form).

(我已经更改了名称,file因为file()它已经是 Python 中的一个内置函数,而将这个名称重用于其他东西是不好的形式)。



Or you could use a dictionary comprehension instead, starting with your items list:

或者您可以改用字典理解,从您的项目列表开始:

itemDict = {item[0]: item[1:] for item in items}

回答by Patrick Yu

Assuming you want your dictionary key to be the 1st element of the list, here is an implementation:

假设您希望您的字典键是列表的第一个元素,这里是一个实现:

list = [[1, 30, 5], [2, 64, 4]]
dict = {}

for l2 in list:
    dict[l2[0]] = l2[1:]

It works by iterating through list, and the sub-list l2. Then, I take the 1st element of l2and assign it as a key to dict, and then take the rest of the elements of l2and put it as the value.

它通过迭代list和子列表来工作l2。然后,我取 的第一个元素l2并将其分配为 的键dict,然后取其余的元素l2并将其作为值。

The result is the finished dictionary {1: [30, 5], 2: [64, 4]}

结果是完成的字典 {1: [30, 5], 2: [64, 4]}