Python:字典清单清单 [英] Python: List of lists to dictionary

查看:100
本文介绍了Python:字典清单清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

列表的当前格式如下:

[[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

推荐答案

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

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

成为

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

所以...

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

(而且我已经更改了file的名称,因为file()已经是Python中的内置函数,并且将其重用是其他不好的形式).

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

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

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

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

这篇关于Python:字典清单清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆