且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Python中通过嵌套字典循环

更新时间:2022-10-17 21:27:15

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

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

  out_region =无out_value =无sel_serie ='孕产妇死亡率(每十万人口的死亡人数)'min_year = 2005max_year = 2015对于reg,在dict_total.items()中为dict_reg:打印(reg)对于dict_reg.items()中的dict_year:如果min_year< =年< = max_year:印刷(年)对于意甲,在dict_year.items()中的值:如果serie == sel_serie且值不为None:print('{} {}'.format(serie,value))如果out_value为None或out_value<价值:out_value =值out_region = regprint('Region:{} \ nSerie:{} Value:{}'.format(out_region,sel_serie,out_value)) 

So I need help looping thru a nested dictionaries that i have created in order to answer some problems. My code that splits up the 2 different dictionaries and adds items into them is as follows: Link to 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

When I print the dictionary region_data output is:

For Clarification What is shown is a "Region" as a key in a dict. The years being Values and keys in that 'Region's Dict and so on so forth....

I want to understand how i can loop thru the data and answer a question like :

Which region had the largest numeric decrease in Maternal mortality ratio from 2005 to 2015?

Were "Maternal mortality ratio (deaths per 100,000 population)" is a key within the dictionary.

If you prefer to loop throught dictionaries in Python 3.x you can use the method .items() from each dictionary and nest them with three loops.

With a main dictionary called hear dict_total, this code will work it.

out_region = None
out_value = None
sel_serie = 'Maternal mortality ratio (deaths per 100,000 population)'
min_year = 2005
max_year = 2015

for reg, dict_reg  in dict_total.items():
    print(reg)
    for year, dict_year in dict_reg.items():
        if min_year <= year <= max_year:
            print(year)
            for serie, value in dict_year.items():
                if serie == sel_serie and value is not None:
                    print('{} {}'.format(serie, value))
                    if out_value is None or out_value < value:
                        out_value = value
                        out_region = reg

 print('Region: {}\nSerie: {} Value: {}'.format(out_region, sel_serie, out_value))