简体   繁体   English

使用csv文件创建嵌套字典

[英]Create nested dictionary with csv file

I am trying to create several nested dictionaries out of a csv data file. 我试图从csv数据文件中创建几个嵌套的字典。 I am not sure how to properly format the dictionary. 我不确定如何正确格式化字典。

Here is the csv file 这是csv文件

1,Afghanistan,MENA,20-24,Female,Urban,6.786986809,442.6952889,1.53%

I need to pull country , region , age_group , gender , geographic_area , diabetes and population as strings/floats. 我需要拉countryregionage_groupgendergeographic_areadiabetespopulation为字符串/浮动。

The following is my code: 以下是我的代码:

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 }

I am trying to return the finished dictionary D that nests a dictionary of the country inside another dictionary of region inside another one of age group that has the values of the tuple diabetes_data. 我正在尝试返回完成的字典D,该字典将国家的字典嵌套在另一个具有元组Diabet_data值的年龄组中的另一区域词典中。

I am unsure of how to preceded, I am currently using a single for loop and am not sure if I need to have multiple. 我不确定该怎么做,我目前使用单个for循环,也不确定是否需要多个。

The final dictionary should look like the following: 最终的字典应如下所示:

{'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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM