I have a text file in this format (in_file.txt):
banana 4500 9
banana 350 0
banana 550 8
orange 13000 6

How can I convert this into a dictionary list in Python?
Code:
in_filepath = 'in_file.txt'
def data_dict(in_filepath):
with open(in_filepath, 'r') as file:
for line in file.readlines():
title, price, count = line.split()
d = {}
d['title'] = title
d['price'] = int(price)
d['count'] = int(count)
return [d]
The terminal shows the following result:
{'title': 'orange', 'price': 13000, 'count': 6}
Correct output:
{'title': 'banana', 'price': 4500, 'count': 9}, {'title': 'banana', 'price': 350, 'count': 0} , ....
Can anyone help me with my problem? Thank you!
titles = ["title","price","count"]
[dict(zip(titles, [int(word) if word.isdigit() else word for word in line.strip().split()])) for line in open("in_file.txt").readlines()]
or:
titles = ["title","price","count"]
[dict(zip(titles, [(data:=line.strip().split())[0], *map(int, data[1:])])) for line in open("in_file.txt").readlines()]
your approach(corrected):
in_filepath = 'in_file.txt'
def data_dict(in_filepath):
res = []
with open(in_filepath, 'r') as file:
for line in file.readlines():
title, price, count = line.split()
d = {}
d['title'] = title
d['price'] = int(price)
d['count'] = int(count)
res.append(d)
return res
data_dict(in_filepath)
why? because
d = {}
d['title'] = title
d['price'] = int(price)
d['count'] = int(count)
is out of for loop and run only once and when for be finished and then you have just one element
for loop (saving) and at last, return result@Rockbar approach:
import pandas as pd
list(pd.read_csv("in_file.txt", sep=" ", header=None, names=["title","price","count"]).T.to_dict().values())
You can read the file line-by-line and then create dict base keys that define in the first.
keys = ['title', 'price' , 'count']
res = []
with open('in_file.txt', 'r') as file:
for line in file:
# Or in python >= 3.8
# while (line := file.readline().rstrip()):
tmp = [int(w) if w.isdigit() else w for w in line.rstrip().split() ]
res.append(dict(zip(keys, tmp)))
print(res)
[
{'title': 'banana', 'price': 4500, 'count': 9},
{'title': 'banana', 'price': 350, 'count': 0},
{'title': 'banana', 'price': 550, 'count': 8},
{'title': 'orange', 'price': 13000, 'count': 6}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With