在Python中通过嵌套字典循环

时间:2019-04-10 19:41:02

标签: python csv dictionary

因此,我需要帮助通过我创建的嵌套字典进行循环,以回答一些问题。我的代码将2个不同的字典拆分并添加到其中,如下所示: 链接到csv: https://docs.google.com/document/d/1v68_QQX7Tn96l-b0LMO9YZ4ZAn_KWDMUJboa6LEyPr8/edit?usp=sharing

import csv
region_data = {}
country_data = {}
answers = []
data = []

cuntry = False
f = open('dph_SYB60_T03_Population Growth, Fertility and Mortality Indicators.csv')

reader = csv.DictReader(f)

for line in reader:
  #This gets all the values into a standard dict
  data.append(dict(line))  

#This will loop thru the dict and create variables to hold specific items
for i in data: 
  # collects all of the Region/Country/Area
  location = i['Region/Country/Area'] 
  # Gets All the Years
  years = i['Year']
  i_d = i['ID']
  info = i['Footnotes']
  series = i['Series']
  value = float(i['Value'])
  # print(series)
  stats = {i['Series']:i['Value']}
  # print(stats)
  # print(value)

  if (i['ID']== '4'):
    cuntry = True
  if cuntry == True:
    if location not in country_data:
      country_data[location] = {}
    if years not in country_data[location]:
      country_data[location][years] = {}
    if series not in country_data[location][years]:
      country_data[location][years][series] = value

  else:
    if location not in region_data:
      region_data[location] = {}
    if years not in region_data[location]:
      region_data[location][years] = {}
    if series not in region_data[location][years]:
      region_data[location][years][series] = value

当我打印字典时,region_data输出为: enter image description here

为澄清起见,显示的是“区域”作为字典中的键。年份是该“地区字典”中的值和键,依此类推。...

我想了解如何遍历数据并回答类似问题:

从2005年到2015年,哪个地区的孕产妇死亡率下降幅度最大?

“孕产妇死亡率(每10万人的死亡)”是词典中的关键。

2 个答案:

答案 0 :(得分:1)

  1. 构建数据框

为此使用大熊猫,并阅读与此answer相关的文件。

import pandas as pd
filename = 'dph_SYB60_T03_Population Growth, Fertility and Mortality Indicators.csv'
df = pd.read_csv(filename)
  1. 构建数据透视表

然后,您可以将“区域/国家/地区”和“系列”作为枢轴,并用作汇总函数“ max”。

pivot = df.pivot_table(index='Region/Country/Area', columns='Series', values='Value', aggfunc='max')
  1. 按您感兴趣的顺序排序

然后按系列名称对“数据透视表”进行排序,并使用参数“升序”

df_sort = pivot.sort_values(by='Maternal mortality ratio (deaths per 100,000 population)', ascending=False)
  1. 提取第一行中的最大值。

最后,您将得到问题的答案。

df_sort['Maternal mortality ratio (deaths per 100,000 population)'].head(1)


Region/Country/Area
Sierra Leone    1986.0
Name: Maternal mortality ratio (deaths per 100,000 population), dtype: float64
  

警告:您的某些区域在2005年之前有记录,因此您应该仅针对2005年到2015年之间的值过滤数据。

答案 1 :(得分:1)

如果您希望在Python 3.x中遍历所有字典,则可以使用每个字典中的.items()方法并将其嵌套三个循环。

使用一个名为listen dict_total的主词典,此代码将起作用。

BigEgg2.Yolk.f()
相关问题