Search code examples
pythonlistdictionaryhashmapmapping

trying to get value from a dict with integer key


I am working with a dict which is structured like this inside a function:

listOfInformation = [{123456789: {'PokemonId': '123456789', 'PokemonName': 'Pikachu', 'PokemonAttack': 'thunderbolt'}}]

In that function, I'm passing an integer as an argument (pokemon_id) and then trying to test if the key-value pair exists like this:

listOfInformation(pokemon_id)

But I am getting an error of IndexError, list index out of range. I can't figure out why would I get this error. how can I fix this?

I should be getting back the whole value of this:

{'PokemonId': '123456789', 'PokemonName': 'Pikachu', 'PokemonAttack': 'thunderbolt'}

Solution

  • Your data structure appears to be a list containing one element, which is a dictionary. If so, you should be using:

    listOfInformation = [{123456789: {'PokemonId': '123456789', 'PokemonName': 'Pikachu', 'PokemonAttack': 'thunderbolt'}}]
    if 123456789 in listOfInformation[0]:
        print(listOfInformation[0][123456789])
    

    The above prints:

    {'PokemonId': '123456789', 'PokemonAttack': 'thunderbolt', 'PokemonName': 'Pikachu'}