Trying to access a value inside a dictionary in Python, but I get an error when printing run the code

Asked

Viewed 54 times

-2

I was creating a dictionary playing with python Pokemon in pycharm Comunity, but when I went to perform the dictionary access, I was returned an error message in the code when trying to print one of the values inside a key in the dictionary that in turn there are also other dictionaries inside:

print(f'O pokemon {pesquisa} é de estagio {pk["stage"]}')

Typeerror: string indices must be integers

In case to make the code start running you need to write Charmander I am beginner in python and I would like to know how to solve this, follow the code below:

pokemons = {
    'Charmander': {
        'stage': '1',
        'tipo': 'fogo',
        'evoluções': {
            'charmilion': {
                'stage': '2',
                'tipo': 'fogo',
                'evoluções': {
                    'charizard': {
                        'stage': '3',
                        'tipo': 'fogo/voador',
                    },
                },
            },
        },
    },
}

pesquisa = str(input('Qual pokemon gostaria de saber mais sobre? '))
if pesquisa in pokemons:
    for pk, pv in pokemons[pesquisa].items():
        print(f'O pokemon {pesquisa} é de estagio {pk["stage"]}')
else:
    print('Este pokemon não existe')

1 answer

1


The mistake happens because in your loop, pk is the name of the key, thus a string. To string can only have whole index.

>>> a = "Teste"
>>> a["stage"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

>>> a[1]
'e'

Being asism, just change this part

if pesquisa in pokemons:
    for pk, pv in pokemons[pesquisa].items():
        print(f'O pokemon {pesquisa} é de estagio {pk["stage"]}')

for

if pesquisa in pokemons:
   print(f'O pokemon {pesquisa} é de estagio {pokemons[pesquisa].get("stage", "não tenho esta informação")}')

The use of get is to give the opportunity in the case of key stage no code exists do not generate an exception.

There are other ways, but this would be within your logic.

Update

To catch the evolutions would be something like below:

if pesquisa in pokemons:
   print(f"{pesquisa} é um pokemon no estágio {pokemons[pesquisa]['stage']}")
   for pokemon2, dados_pokemon2 in pokemons[pesquisa]['evoluções'].items():
       print(f"{pokemon2} é evolução de {pesquisa} e é estágio {dados_pokemon2['stage']}")
       for pokemon3, dados_pokemon3 in dados_pokemon2['evoluções'].items():
           print(f"{pokemon3} é evolução de {pokemon2} e é estágio {dados_pokemon3['stage']}")

I hope it helps.

  • I understood thank you very much, it helped a lot, but what about in case I want to print after that the evolutions? Type after printing this also print in the same way the information of the evolutions, for example 'The Pokemon Charmande is of stage 1' from below 'being its evolutions: Charmilion of stage 2'. How would I access this second dictionary and print out your keys?

  • @Kaique, check the update.

  • thank you very much, helped me understand much more now, very grateful.

  • @Kaique, I’m glad you helped. If you think it’s relevant, mark the answer as a solution and vote positive. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.