r/pythonhelp • • Dec 07 '22

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?

2 Upvotes

5 comments sorted by

1

u/Goobyalus Dec 07 '22
  • listOfInformation is a list of dictionaries. It is not a dictionary or a function.

  • listOfInformation(pokemon_id) attempts to call listOfInformation as though it were a function, which will TypeError.

  • listOfInformation[pokemon_id] will attempt to index the list at element pokemon_id, which if it's 123456789, is out of bounds of the single-element list.

  • I think you meant to define something like

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

    and access it like

      pokemon_dict[pokemon_id]

2

u/[deleted] Dec 07 '22

Oh sorry, (fixed it in the question) yes I meant to put the square brackets in listOfInformation(pokemon_id) But the reason I want to have the key-value pairs inside the square brackets is because I want to have multiple pairs like this:

pokemon_dict = [{123456789: {'PokemonId': '123456789', 'PokemonName': 'Pikachu', 'PokemonAttack': 'thunderbolt'}}, {45736238: {'PokemonId': '45736238', 'PokemonName': 'some_name', 'PokemonAttack': 'some_attack'}}]

are you saying that the square bracket is not necessary? even if I want to have multiple key-value pairs?

1

u/Goobyalus Dec 07 '22 edited Dec 07 '22

are you saying that the square bracket is not necessary? even if I want to have multiple key-value pairs?

Yeah, you're already doing that with the inner dictionary that has three key-value pairs:

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

same idea:

{
    1: { "PokemonId": 1, "PokemonName": ..., "PokemonAttack": ...,},
    2: { "PokemonId": 2, "PokemonName": ..., "PokemonAttack": ...,},
    3: { "PokemonId": 3, "PokemonName": ..., "PokemonAttack": ...,},
    123456789: {
        'PokemonId': '123456789',
        'PokemonName': 'Pikachu',
        'PokemonAttack': 'thunderbolt',
    },
}

and you access the dictionary values by key (as opposed to positional index like in a list) with the square bracket syntax. my_dict[123456789].

2

u/[deleted] Dec 07 '22

that makes total sense. thank you very much !

1

u/Goobyalus Dec 07 '22

You're welcome