[英]How to read a txt file and create a dictionary with each key having list of values in python?
我正在閱讀一個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
我想創建一個字典,使每個單詞都是一個鍵,其值是數字列表,例如:
{in : [0.017077, -0.073018, 0.094730, -0.026420, 0.272884], and : [0.2, 0.3, 0.5 ,0.6]....}
我怎樣才能做到這一點? 目前,我正在做類似的事情:
with open('file.txt','r') as text:
for line in text:
key, value = line.split()
res[key] = int(value)
print res
但這給了我錯誤: too many values to unpack
line.split()
返回值列表,python無法告訴您如何在key
和value
之間分割它們,您需要對此進行明確說明
嘗試:
vals = line.split()
key = vals[0]
value = [float(x) for x in vals[1:]]
res[key] = value
問題是
key, value = line.split()
例如
>>> 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
拆分會返回兩個以上的值,您正在嘗試獲取2個變量中的值。
你可以試試
key , value = line.split()[0], line.split[1:]
您犯了兩個錯誤-第一個錯誤是在兩個變量中解壓縮兩個以上的值,第二個錯誤是使用int()強制轉換來獲取float。
最簡單的解決方案是使用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
請記住,在python 3.x中,您可以直接執行以下操作:
key, *values = line.split()
更簡潔的版本使用字典理解:
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.