Reputation: 171
I have this program:
def file(fname):
lines = open(fname).read().splitlines()
return(lines)
print(file('venue.txt'))
And it came out like this which I change into list:
['room 1, 10, 250']
How do I build a dictionary data with it, so that it can be like this:
[{'name': 'room 1', 'max': 10, 'cost': 250}]
Some clue maybe for me to build it. Thanks
Edited:
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'))
It prints:
new.append({'name':split[0],'max':split[1],'cost':split[2]})
IndexError: list index out of range
What does it mean?
Upvotes: 2
Views: 56
Reputation: 71471
You can try this:
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)
Upvotes: 1
Reputation: 5971
If they are separated by ', '
you can use the split()
on ', '
.
Will return an array with the separated items.
For your example:
current_list = ['room 1, 10, 250']
split = current_list[0].split(', ')
new_list = [{'name': split[0], 'max': int(split[1]), 'cost': int(split[2])}]
print(new_list)
output:
[{'name': 'room 1', 'max': 10, 'cost': 250}]
For a larger list:
current_list = ['room 1, 10, 250', 'room 2, 30, 500','room 3, 50, 850']
new_list = []
for i in current_list:
split = i.split(', ')
new_list.append({'name': split[0], 'max': int(split[1]), 'cost': int(split[2])})
print(new_list)
output:
[{'name': 'room 1', 'max': 10, 'cost': 250}, {'name': 'room 2', 'max': 30, 'cost': 500}, {'name': 'room 3', 'max': 50, 'cost': 850}]
Upvotes: 1