Values of a nested dictionary

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

hello, So i am trying to access the “cost” and “wear” to use the values but don’t really know how to.

This is the dictionary:

var shop_items = {
“Engine”: {
“Ignition Coils”:{“cost”:30, “wear”:0},
“Spark Plugs”:{“cost”:40, “wear”:0}
“Brakes”: {
“Brake Pads”:{“cost”:50, “wear”:0},
“Brake Discs”:{“cost”:70, “wear”:0},
“Cylinder”:{“cost”:30, “wear”:0}

i tried with this in a for loop but it returns null:


If somebody can tell me how to get the cost and wear values, i will really appreciate. Thank you

:bust_in_silhouette: Reply From: codeestuary

The way I like to access stuff from dictionaries is like this

This will return the 30 in your code.

I think get() on a Dictionary is only more useful in some cases because it returns null rather than throwing an error if a key is missing. In my opinion I’d rather have an error thrown if my Dictionary isn’t setup right or isn’t being accessed right.

:bust_in_silhouette: Reply From: wyattb

Here is an example how you can work with Dictionaries and how you can iterate over one.

func _ready() -> void:
    # get values
	print(shop_items["Engine"]["Ignition Coils"]["cost"])
	# Iterate 
	for items in shop_items:
		print(items, shop_items[items])
		for part_func in shop_items[items]:
			for properties in shop_items[items][part_func]:
				print(properties, " ", shop_items[items][part_func][properties])