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

标签 python dictionary

文本文件:

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/

相关文章:

python - Flask:Peewee model_to_dict 助手不起作用

python - 使用python3.5的aiohttp查询get URL的参数

ios - 如何在swift 4中对字典数组进行排序

java - 用于本地化的 map 表示

c# - 如何在类构造函数中初始化字典

python - 带有文件名通配符的 Django call_command()

python - Process.StandardOutput.Readline() 卡在 Mono 而不是 .NET

python - 为什么我没有看到 Numpy 的 DeprecationWarning?

java - 映射java int流

python - python 将具有相同键值对的多个字典合并为一个字典