我要讀取一個文件并將其作為字典返回,其中 KEY 為 arg[2] 索引為 0,相應的值為 file.csv 行中的 arg[3] 和 arg[5],其中每個值都是一個列表元組。我怎樣才能做到這一點,例如不使用導入。我對此的看法:dict= {}with open('filename.csv') as file: file.readline() for line in file: iso_code,continent,location,date,cases,newer_cases = (s.strip('"') for s in line.split(',')) key = (location) if key not in answer: dict[key] = {} 現在我只是輸出每個國家的很多重復項。有沒有更聰明的方法來做到這一點,我如何知道每個鍵是否是元組列表?**文件中的片段**iso_code,continent,location,date,cases,newer_casesaaa,bbb,helsinki,2020.05.18,5,4aaa,bbb,helsinki,2020.05.22,4,8aaa,bbb,copenhagen,2020.07.19,8,aaa,bbb,oslo,2020.02.03,10,19aaa,bbb,oslo,2019.02.18,21,2aaa,bbb,oslo,2019.02.18,,13預期輸出的關鍵應該是國家/地區名稱(str),值包含日期、案例(str)元組列表。如果箱子是空的,則不應添加。
1 回答

回首憶惘然
TA貢獻1847條經驗 獲得超11個贊
檢查這是否是您的預期輸出
my_dict= {}
with open('filename.csv') as file:
file.readline()
for line in file:
iso_code,continent,location,date,cases,newer_cases = (s.strip('"') for s in line.split(','))
if cases :
if location not in my_dict:
my_dict[location] = [(date,cases)]
else:
my_dict[location].append((date,cases))
print(my_dict)
添加回答
舉報
0/150
提交
取消