gpt4 book ai didi

python - 如何使用 for 循环创建字典列表?

转载 作者:行者123 更新时间:2023-12-01 02:30:55 24 4
gpt4 key购买 nike

文本文件:

VIP Room,      10,   250
Executive Room,30, 500
Pool Site, 50, 850
Banquet Hall, 200, 1000
Chamber Hall, 500, 2000
Concert Hall, 1000, 3500

到目前为止,我的代码用于读取文件并创建列表:

def readVenueList():
dic={}
venueList=[]
f=open("venue.txt","r")
for line in f:
line = line.split(",")
print(line)
for i in line:
i.split()
dic["name"]=i[0]
dic["num"]=i[1]
dic["cost"]=i[2]
venueList.append(dic)
return(venueList)

如何创建具有以下输出的字典列表?

venueList = [{'cost': '250', 'name': 'VIP Room', 'num': '10'},
{'cost': '250', 'name': 'Executive Room', 'num': '30'},
# and so on and so forth...
]

最佳答案

您可以简单地使用 csv 读取器库来处理此问题。

import csv
headers = ['name', 'num', 'cost']
with open('venue.txt', 'r') as f:
reader = csv.reader(f)
needed_list = [{headers[i]: row[i].strip() for i in range(3)} for row in reader]

关于python - 如何使用 for 循环创建字典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46821838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com