Reinaldo Chaves
Reinaldo Chaves

Reputation: 995

Error creating dictionary with API data - string indices must be integers

In Python3 I made a program to read an API (from the Brazilian Chamber of Deputies) and get the data in JSON:

import requests
url = 'https://dadosabertos.camara.leg.br/api/v2/deputados'

# first create a dictionary with the names and links of each deputy
deputados = {}
for pagina in [1, 2, 3, 4, 5, 6]:
    parametros = {'formato': 'json', 'itens': 100, 'pagina': pagina}
    resposta = requests.get(url, parametros)
    for deputado in resposta.json()['dados']:
        deputados[deputado['nome']] = deputado['uri']

# then read each link and create a dictionary with the data of each deputy
perfis = {}
for chave, valor in deputados.items():
    print(valor)
    print(chave)
    resposta = requests.get(valor)
    for linha in resposta.json()['dados']:
        perfis[chave] = linha['uri']
        perfis[chave]= linha['nomeCivil']
    for linha2 in resposta.json()['ultimoStatus']:
        perfis[chave] = linha2['nomeEleitoral']
        perfis[chave] = linha2['siglaPartido']
        perfis[chave] = linha2['siglaUf']
        perfis[chave]= linha2['urlFoto']
    for linha3 in resposta.json()['ultimoStatus/gabinete']:
        perfis[chave] = linha3['telefone']
        perfis[chave] = linha3['email']
        perfis[chave] = linha3['sexo']
        perfis[chave] = linha3['dataNascimento']

But I had this error message:

https://dadosabertos.camara.leg.br/api/v2/deputados/178957
ABEL MESQUITA JR.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-067597090c77> in <module>()
      5     resposta = requests.get(valor)
      6     for linha in resposta.json()['dados']:
----> 7         perfis[chave] = linha['uri']
      8         perfis[chave]= linha['nomeCivil']
      9     for linha2 in resposta.json()['ultimoStatus']:

TypeError: string indices must be integers

Here is an example of the data of a page:

resposta = requests.get('https://dadosabertos.camara.leg.br/api/v2/deputados/178957')
print(resposta.json())
{'dados': {'id': 178957, 'uri': 'https://dadosabertos.camara.leg.br/api/v2/deputados/178957', 'nomeCivil': 'ABEL SALVADOR MESQUITA JUNIOR', 'ultimoStatus': {'id': 178957, 'uri': 'https://dadosabertos.camara.leg.br/api/v2/deputados/178957', 'nome': 'ABEL MESQUITA JR.', 'siglaPartido': 'DEM', 'uriPartido': 'https://dadosabertos.camara.leg.br/api/v2/partidos/36769', 'siglaUf': 'RR', 'idLegislatura': 55, 'urlFoto': 'http://www.camara.leg.br/internet/deputado/bandep/178957.jpg', 'data': '2015-02-01', 'nomeEleitoral': 'ABEL MESQUITA JR.', 'gabinete': {'nome': '248', 'predio': '4', 'sala': '248', 'andar': '2', 'telefone': '3215-5248', 'email': '[email protected]'}, 'situacao': 'Exercício', 'condicaoEleitoral': 'Titular', 'descricaoStatus': None}, 'cpf': '', 'sexo': 'M', 'urlWebsite': None, 'redeSocial': [], 'dataNascimento': '1962-03-29', 'dataFalecimento': None, 'ufNascimento': 'RR', 'municipioNascimento': 'Boa Vista', 'escolaridade': 'Superior Incompleto'}, 'links': [{'rel': 'self', 'href': 'https://dadosabertos.camara.leg.br/api/v2/deputados/178957'}]}

Please, does anyone know why the error occurred while creating the second dictionary and starting to supply it?

Upvotes: 1

Views: 48

Answers (2)

Gsk
Gsk

Reputation: 2945

With the for loops, you are accessing each key of your dictionary (which is a string), and tring to index that string with another string: basically, you're calling "id"["uri"].

You can avoid the for loop and access your variable directly; something like this should work:

perfis = {}
for chave, valor in deputados.items():
    print(valor)
    print(chave)
    resposta = requests.get(valor)
    answer = resposta.json()

    perfis.setdefault(chave, {})['uri'] = answer['dados']['uri']
    perfis.setdefault(chave, {})['nomeCivil'] = answer['dados']['nomeCivil']

    perfis.setdefault(chave, {})['nomeEleitoral'] = answer['dadultimoStatusos']['nomeEleitoral']
    perfis.setdefault(chave, {})['siglaPartido'] = answer['dadultimoStatusos']['siglaPartido']
    perfis.setdefault(chave, {})['siglaUf'] = answer['dadultimoStatusos']['siglaUf']
    perfis.setdefault(chave, {})['urlFoto'] = answer['dadultimoStatusos']['urlFoto']

    perfis.setdefault(chave, {})['telefone'] = answer['ultimoStatus/gabinete']['telefone']
    perfis.setdefault(chave, {})['email'] = answer['ultimoStatus/gabinete']['email']
    perfis.setdefault(chave, {})['sexo'] = answer['ultimoStatus/gabinete']['sexo']
    perfis.setdefault(chave, {})['dataNascimento'] = answer['ultimoStatus/gabinete']['dataNascimento']

Upvotes: 1

Amir Rachum
Amir Rachum

Reputation: 79685

When you iterate over a dictionary (resposta.json()['dados']), the default iteration in on the keys of the dictionary. So linha will be id or uri, etc. That's why you get string indices must be integers. It's hard for me to understand what you're trying to do since it's not in English, but if you just want to extract information from the json dictionary, you might want to do this:

json_res = reposta.json()
perfis.update(json_res['dados'])
perfis.update(json_res['ultimoStatus'])

Upvotes: 1

Related Questions