[英]How to read a txt file and create a dictionary with each key having list of values in python?
I am reading a txt file, which is of the form: 我正在阅读一个txt文件,其格式为:
in 0.01 -0.07 0.09 -0.02 0.27
and 0.2 0.3 0.5 0.6
to 0.87 0.98 0.54
from 1.2 5.4 0.2 0.4
I want to create a dictionary such that each word is a key and its value is the list of numbers, like: 我想创建一个字典,使每个单词都是一个键,其值是数字列表,例如:
{in : [0.017077, -0.073018, 0.094730, -0.026420, 0.272884], and : [0.2, 0.3, 0.5 ,0.6]....}
How can I do that? 我怎样才能做到这一点? Currently I'm doing something like: 目前,我正在做类似的事情:
with open('file.txt','r') as text:
for line in text:
key, value = line.split()
res[key] = int(value)
print res
But it gives me error: too many values to unpack
但这给了我错误: too many values to unpack
line.split()
returns a list of values, python can't tell how you'd want to split them between key
and value
, you need to be explicit about this line.split()
返回值列表,python无法告诉您如何在key
和value
之间分割它们,您需要对此进行明确说明
try: 尝试:
vals = line.split()
key = vals[0]
value = [float(x) for x in vals[1:]]
res[key] = value
The problem is 问题是
key, value = line.split()
For example 例如
>>> a = "in 0.01 -0.07 0.09 -0.02 0.27"
>>> a.split()
['in', '0.01', '-0.07', '0.09', '-0.02', '0.27']
>>> x, y = a.split()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
Split returns more than 2 values and your are trying to get those in 2 variables. 拆分会返回两个以上的值,您正在尝试获取2个变量中的值。
You can try 你可以试试
key , value = line.split()[0], line.split[1:]
You make two errors - the first is to unpack more than 2 values in two variables, the second is use int() casting to obtain float. 您犯了两个错误-第一个错误是在两个变量中解压缩两个以上的值,第二个错误是使用int()强制转换来获取float。
The simplest solution is like this using python 2.x: 最简单的解决方案是使用python 2.x:
res = dict()
with open('file.txt','r') as text:
for line in text:
record = line.split()
key = record[0]
values = [float(value) for value in record[1:]]
res[key] = values
print res
Remember that in with python 3.x you can directly do this: 请记住,在python 3.x中,您可以直接执行以下操作:
key, *values = line.split()
A more concise version use dictionary comprehension: 更简洁的版本使用字典理解:
with open('file.txt','r') as text:
res = {line.split()[0]: [v for v in map(float, line.split()[1:])] for line in text}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.