我正在嘗試解決任務:
- 從“區域”、“范圍”和“人口”列中讀取資料。
Region Range Population Region1 23 1299 Region1 34 3400 Region2 24 3200 Region2 34 1209 Region2 45 3008
- 存盤每個范圍和區域的總人口,使得 data_dict 具有結構 data_dict[region][range],其中的值對應于人口。例如,data_dict["Region1"]["23"] 應該包含區域“Region1”中 23 歲的人數。
我想像這樣使用嵌套字典
{‘Region1:{23:1299} ,’Region1’:{34:3400} ….}
它允許訪問
data_dict[‘Region1’][ ‘34’] = 3400
編碼:
with open(self.file_name, encoding='iso-8859-1') as file:
reader = csv.DictReader(file)
for line in reader:
self.data_dict[line['Region']] = {line['Range']:line['Population']}
但它不能按預期作業,因為字典中的鍵應該是唯一的,當我從檔案中添加資料時,它會覆寫值并且只有最后一個是可訪問的,并且它不會將最頂層的資料放入字典中。
我將不勝感激任何幫助。謝謝你。
uj5u.com熱心網友回復:
您需要檢查密鑰是否已經存在。如果它不存在,請執行您正在做的事情,否則將一個鍵添加到現有字典中。
with open(self.file_name, encoding='iso-8859-1') as file:
reader = csv.DictReader(file)
for line in reader:
if line['Region'] in data_dict.keys():
self.data_dict[line['Region']][line['Range']] = line['Population']
else:
self.data_dict[line['Region']] = {line['Range']:line['Population']}
最終的資料結構看起來更像:
{
"Region1": {
"24": 1299,
"34": 3400
},
"Region2": {
"24": 3200,
"34": 1209,
"45": 3008
}
}
但它允許以您描述的方式訪問data_dict['Region']['Range']。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/518649.html
