简体   繁体   中英

Python Error: TypeError: list indices must be integers or slices, not str

i get this error in this line : valor_mensal_aux[i] = int(data['Dados'][0][json_date][0]['valor'])

i tried to post some code here so you guys can get context for all the variables:

if len(imobs) == 0:

   year_codes = ["2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020"]

   month_codes = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]

   city_codes = ["1111609", "1120303", "11A1312", "11D1714", "11E0402", "16D0105", "16E0603", "16F1009", "16G1823",
                 "16H0502", "16J0907", "1701106", "1701512", "1840205", "1851416", "1861214", "1870705", "1500805"]

   valor_mensal_aux = [0]
   valor_anual = [0][0]
   # valor_anual_ano_inicial = [18] # array com valor anual de cada cidade para ano inicial
   # valor_anual_ano_final = [18] # array com valor anual de cada cidade para ano final

   for city_code in city_codes:

       for year_code in year_codes:

           for month_code in month_codes:

               url_imob = Request(
                   "https://www.ine.pt/ine/json_indicador/pindica.jsp?op=2&varcd=0010042&Dim1=S3A" + year_code + \
                   month_code + "&Dim2=" + city_code + "&Dim3=T&lang=PT", headers={'User-Agent': 'XYZ/3.0'})
               json_date = year_code + month_code
               response = urlopen(url_imob)
               data = json.loads(response.read())
               i = 0
               while i < 12:
                   valor_mensal_aux[i] = int(data['Dados'][0][json_date][0]['valor'])
                   i += 1

           valor_anual[data['geodsg']][year_code] = statistics.mean(valor_mensal_aux)

           python_imob = Imob(year_code, valor_anual[city_code][year_code], data['DataUltimoAtualizacao'],
                              data['Dados'][json_date]['geodsg'])
           session.add(python_imob)  
           session.commit()
           session.close()
           imobs = session.query(Imob).all() 

What can i change to solve it? And i hope there are no more errors after this line of code as well :)

I tried accessing the web page concerned, and a typical object loaded from the JSON response looks like this:

[{'Dados': {'201101': [{'dim_3': 'T',
                        'dim_3_t': 'Total',
                        'geocod': '1111609',
                        'geodsg': 'Viana do Castelo',
                        'valor': '779'}]},
  'DataExtracao': '2020-09-03T14:21:27.691+01:00',
  'DataUltimoAtualizacao': '2020-08-27',
  'IndicadorCod': '0010042',
  'IndicadorDsg': 'Valor mediano de avaliação bancária (€/ m²) por Localização '
                  'geográfica (Município - 2013) e Tipo de construção; Mensal '
                  '- INE, Inquérito à avaliação bancária na habitação',
  'MetaInfUrl': 'https://www.ine.pt/bddXplorer/htdocs/minfo.jsp?var_cd=0010042&lingua=PT',
  'UltimoPref': 'Julho de 2020'}]

This means that you need to access it like this:

data[0]['Dados'][json_date][0]['valor']

You had instead:

data['Dados'][0][json_date][0]['valor']

You will also have issues with trying to assign off the end of the list. You probably want something like this:

       for year_code in year_codes:
           valor_mensal_aux = []
           for month_code in month_codes:
                ......
                valor_mensal_aux.append(int(data[0]['Dados'][json_date][0]['valor']))

and do not loop over i inside your month loop - only append it once for each month.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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