我正在遍历CSV文件,并希望将基于给定列的所有常见行分组为一个字典,该字典中填充了该行的其余值。
示例:
Date, Name, Gender, Address
01/02/2019, John Doe, Male, 1 example street
21/12/2018, Mary Robinson, Female, 2 Lane St.
05/06/2017, John Doe, Male, 1 example street
dates = []
names = []
genders = []
addresses = []
for row in readFile:
date = row[0]
name = row[1]
gender = row[2]
address = row[3]
names.append(name)
dates.append(dates)
genders.append(gender)
addresses.append(address)
if name not in names:
#Create Dictionary with using the value of name. (exec?)
#Then populate dictionary with rest of row.
所以我应该以两个词典结尾。一个叫John Doe,另一个叫 玛丽·鲁滨逊。
例如:
MaryRobinson = {
"date": "21/12/2018",
"name": "Mary Robinson",
"gender": "Female",
"Address": "2 Lane St."
}
也许我最好使用列表,因为我想保留存储多个地址的选项。
我不明白如何从变量值动态创建列表。 我读过这是不好的做法。
注意:大学作业。
答案 0 :(得分:1)
如果愿意,可以用exec
来做,但是我认为这对您的情况不是真的有用(然后您每次想访问它们时都必须再次评估名称字符串) )。我建议您得到一本“主”字典,其中将名称作为键,将字典作为值。可能是以下内容(实际上尚未运行):
data = {}
names = []
for row in readFile:
date = row[0]
name = row[1]
gender = row[2]
address = row[3]
names.append(name)
if name not in names:
data[name] = {"date":date, "gender":gender, "address":address}