[英]Create nested dictionary with csv file
我試圖從csv數據文件中創建幾個嵌套的字典。 我不確定如何正確格式化字典。
這是csv文件
1,Afghanistan,MENA,20-24,Female,Urban,6.786986809,442.6952889,1.53%
我需要拉country
, region
, age_group
, gender
, geographic_area
, diabetes
和population
為字符串/浮動。
以下是我的代碼:
diabetes_data = []
D = {}
fp.readline()
for line in fp:
line = line.split(',')
country = str(line[1])
region = str(line[2])
age_group = str(line[3])
gender = str(line[4])
geographic_area = str(line[5])
diabetes = int(float(line[6])*1000)
population = int(float(line[7])*1000)
tup = (gender, geographic_area, diabetes, population)
diabetes_data.append(tup)
D = {country: region: age_group: diabetes_data }
我正在嘗試返回完成的字典D,該字典將國家的字典嵌套在另一個具有元組Diabet_data值的年齡組中的另一區域詞典中。
我不確定該怎么做,我目前使用單個for循環,也不確定是否需要多個。
最終的字典應如下所示:
{'MENA': {'Afghanistan': {'20-24': [('Female', 'Urban', 6786,
442695), ('Male', 'Urban', 2699, 474429)], '35-39': [('Female',
'Urban', 17834, 237228), ('Male', 'Urban', 14852, 262910)], '50-54':
[('Female', 'Urban', 21715, 117219), ('Male', 'Urban', 23055,
126786)], ... and so on
D[region] = {country: {age_group: diabetes_data}}
這將在另一個字典內的字典中創建一個字典,該字典的值為元組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.