开发者

trying to get value from a dict with integer key

开发者 https://www.devze.com 2022-12-07 21:29 出处:网络
I am working with a dict which is structured like this inside a function: listOfInformation = [{123456789: {\'PokemonId\': \'123456789\', \'PokemonName\': \'Pikachu\', \'PokemonAttack\': \'thunderbo开

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

listOfInformation = [{123456789: {'PokemonId': '123456789', 'PokemonName': 'Pikachu', 'PokemonAttack': 'thunderbo开发者_C百科lt'}}]

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'}


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'}
0

精彩评论

暂无评论...
验证码 换一张
取 消