我有这个程序:
def file(fname):
lines = open(fname).read().splitlines()
return(lines)
print(file('venue.txt'))
结果是这样的,我把它改成了列表:
['room 1, 10, 250']
我如何用它建立字典数据,以便它可以像这样:
[{'name': 'room 1', 'max': 10, 'cost': 250}]
一些线索也许可以帮助我构建它。 谢谢
编辑:
def file(fname):
lines = open(fname).read().splitlines()
new = []
for i in lines:
split = i.split(', ')
new.append({'name':split[0],'max':split[1],'cost':split[2]})
return(new)
print(file('venue.txt'))
它打印:
new.append({'name':split[0],'max':split[1],'cost':split[2]})
IndexError: list index out of range
这是什么意思?
请您参考如下方法:
你可以试试这个:
import re
def file(fname):
lines = open(fname).read().splitlines()
return(lines)
headers = ["name", "max", "cost"]
data1 = [re.split(",\s+", i) for i in file("venue.txt")]
final_data = [{a:b for a, b in zip(headers, data} for data in data1]
print(final_data)
