0 votes

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:

shop_items.get("Engine").get("wear")

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

in Engine by (15 points)

2 Answers

0 votes

The way I like to access stuff from dictionaries is like this
shop_items["Engine"]["Cost"]

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.

by (52 points)
0 votes

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"])
    print(shop_items["Brakes"]["Cylinder"]["wear"])
    # Iterate 
    for items in shop_items:
        print(items, shop_items[items])
        for part_func in shop_items[items]:
            print(part_func,shop_items[items][part_func])
            for properties in shop_items[items][part_func]:
                print(properties, " ", shop_items[items][part_func][properties])
by (805 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.