Accessing dictionaries keys using a for loop

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By bwahaha

I’m having trouble when I try to access a dictionary key using a for loop.
The dictionary is stored in a singleton: (global.gd)

var active_party = ['mc']
var  mc = {LEVEL=1,EXP=0,MAX_HP=200,HP=200,MAX_MP=50,MP=50,STR=5,DEF=5,SPD=5,EVA=5,ACC=5,MAG=5,MDF=5,LCK=5}

And inside the scene:

var speed
for character in global.active_party:
	speed = global.character.SPD

I get "Invalid get index ‘character’ (on base: ‘Node (global.gd)’). "
Is there a way to do this?

Hi,
character isn’t in global in the code you shared. It is local to the for loop scope. Shouldn’t it be speed = character.SPD without the global?

p7f | 2019-01-04 02:04

I don’t get why you would reset the speed var everytime a character is called?

lavaduder | 2019-01-04 13:59

I tried that, p7f, and got “Invalid get index ‘SPD’ (on base: ‘String’).”

‘character’ is iterating the ‘active_party’ array, so at that moment it is the same as ‘mc’, and I confirmed that in the dubugger.

bwahaha | 2019-01-04 17:17

Cause you are iterating over an array active_party that only has an string 'mc' .See my answer below and try that and tell me pls.

p7f | 2019-01-04 17:32

man, i changed the code… have you tried with the exact code that is in the answer? Cause it’s working in my pc.

p7f | 2019-01-04 17:36

:bust_in_silhouette: Reply From: p7f

hi:
I did this and worked in my pc:

var  mc = {LEVEL=1,EXP=0,MAX_HP=200,HP=200,MAX_MP=50,MP=50,STR=5,DEF=5,SPD=5,EVA=5,ACC=5,MAG=5,MDF=5,LCK=5}
var active_party = [mc]

and then:

for character in global.active_party:
    speed = character.SPD

The thing is that when you iterate, you were getting the string ‘mc’, not an object. Now you get the object. This also works for me:

var  mc = {LEVEL=1,EXP=0,MAX_HP=200,HP=200,MAX_MP=50,MP=50,STR=5,DEF=5,SPD=5,EVA=5,ACC=5,MAG=5,MDF=5,LCK=5}
var active_party = {'mc': mc}

Similar but with dictionary, so you can get element by key.
and

for character in global.active_party:
    speed = global.active_party[character].SPD