Accessing data that's held in a dictionary, in a dictionary

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Robster
:warning: Old Version Published before Godot 3 was released.

Hi all,

I have this dictionary in a dictionary (thank you @Nuno Donato).

It looks like this:

#dictionary of dictionaries containing powerup stats
var powerUpDict = {
  "speedUpBat" : {
	imageToUse = "speedUpBat.png",
    batSpeedChange = 10,
    ballSpeedChange = 0,
    freezeBat = false,
    doublePoints = false,
    spawnRandomPowerup = false,
  },
  "slowDownBat" : {
	imageToUse	= "slowDownBat.png",
    batSpeedChange = -10,
    ballSpeedChange = 0,
    freezeBat = false,
    doublePoints = false,
    spawnRandomPowerup = false
	}
}

…that’s all fine. Now I’m trying to retrieve the data:

var selectedPowerUp = powerUpDict[0]
var imageToUse = selectedPowerUp.imageToUse

I get an error Invalid get index '0' (on base: 'Dictionary').… which is ok. I can see that.

What I want to do is run something like:
- randomly select an dictionary in the main database
- get the data out of the info in that sub dictionary

Can anyone offer some guidance on this? It would be really appreciated. Thank you

:bust_in_silhouette: Reply From: derblitzmann

If you call keys() on the outer dictionary, then you should be able to randomly select a key to get one of the inner dictionaries.

Thank you, that was helpful. Much appreciated

Robster | 2017-04-03 22:31

:bust_in_silhouette: Reply From: avencherus
var powerups = powerUpDict.values()
var choice = powerups[randi() % powerups.size() + 1]

for key in choice:
	printt(key, " - ", choice[key])

That was exactly what I needed to figure it out. Much appreciated.
For anyone in the future. Here is how I have it working now:

var powerUpDict = {
  "speedUpBat" : {
	imageToUse = "speedUpBat.png",
    batSpeedChange = 10,
    ballSpeedChange = 0,
    freezeBat = false,
    doublePoints = false,
    spawnRandomPowerup = false,
  },
  "slowDownBat" : {
	imageToUse	= "slowDownBat.png",
    batSpeedChange = -10,
    ballSpeedChange = 0,
    freezeBat = false,
    doublePoints = false,
    spawnRandomPowerup = false
	}
}

#random dude
randomize()

#pick a random sub dictionary from within the main dictionary
var powerups = powerUpDict.values()
var theChosenOne = powerups[randi() % powerups.size()]	

#load the texture stored in the sub dictionary as an object and assign it to the node as the new texture
var loadString = "res://textures/"+theChosenOne.imageToUse
var imageToUse = load(loadString)
get_node("powerUpSprite").set_texture(imageToUse)

Robster | 2017-04-03 22:32

Just a note to this, my example was for readability. If you ever do this with huge dictionaries, it would be more optimal to go with derblitzmann’s suggestion for picking the key. An array of keys is likely faster than an array of dictionaries.

avencherus | 2017-04-04 21:52