[英]Convert a text file into a dictionary list
我有一个这种格式的文本文件(in_file.txt):
banana 4500 9
banana 350 0
banana 550 8
orange 13000 6
如何将其转换为 Python 中的字典列表?
代码:
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]
终端显示以下结果:
{'title': 'orange', 'price': 13000, 'count': 6}
正确的输出:
{'title': 'banana', 'price': 4500, 'count': 9}, {'title': 'banana', 'price': 350, 'count': 0} , ....
谁能帮我解决我的问题? 谢谢!
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()]
或者:
titles = ["title","price","count"]
[dict(zip(titles, [(data:=line.strip().split())[0], *map(int, data[1:])])) for line in open("in_file.txt").readlines()]
你的方法(更正):
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)
为什么? 因为
d = {}
d['title'] = title
d['price'] = int(price)
d['count'] = int(count)
不在for
循环中,只运行一次,当for
完成时,你只有一个元素
for
循环的最后一行(保存),最后返回结果@Rockbar 方法:
import pandas as pd
list(pd.read_csv("in_file.txt", sep=" ", header=None, names=["title","price","count"]).T.to_dict().values())
您正在尝试创建字典列表(对象数组)。 因此,每次从文本行创建字典时,都应该将dictionary
附加到列表中。
代码
in_filepath = 'in_file.txt'
def data_dict(in_filepath):
d = []
with open(in_filepath, 'r') as file:
for line in file.readlines():
title, price, count = line.split()
d.append({'title': title, 'price': int(price), 'count': int(count)})
return d
输出
[
{'title': 'banana', 'price': 4500, 'count': 9},
{'title': 'banana', 'price': 350, 'count': 0},
{'title': 'banana', 'price': 550, 'count': 8},
{'title': 'orange', 'price': 13000, 'count': 6}
]
您可以逐行读取文件,然后创建第一个定义的dict
基本键。
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}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.