I am reading a txt file, which is of the form:
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
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
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.
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.
The simplest solution is like this using 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:
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}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.