I know i just asked a question here, but I looked around and couldn't find an answer, is there any way to get the first item within in a dictionary (PlayerInventory.Inventory[0] was my attempt)

  • Dictionaries are like associate arrays, or hash tables, etc. They have no order. While, the internal representation may be in some order, there is no guarantee of what order, so you should not depend on this.

Dictionaries are like associate arrays, or hash tables, etc. They have no order. While, the internal representation may be in some order, there is no guarantee of what order, so you should not depend on this.

    Dictionaries are not guaranteed to keep the items sorted, so "first item within in a dictionary" isn't really meaningful.

    But if d is a Dictionary, you can do things like d.keys()[0], d.values()[0] and d[d.keys()[0]].

    (I was composing this reply before cybereality's reply appeared.)

    You can do something like this:

    var inventory = {} # data inside here
    
    func _ready():
        for key in inventory.keys():
            print("key: ", key, ", value: ", inventory[key])

    This may be in the order you created the elements, but I wouldn't depend on it. If you really need strict ordering, then Dictionary is not the correct data structure, you should use an Array.

    cybereality OK, that works anyways since I changed the way I was doing this in case of this!

    5 months later

    Yes. While they may be ordered internally in C++, I'm not sure what structure they used (could be a plain array, a linked list, etc.). However, when you use it in your game code, you should not assume any particular order. A Dictionary is not an Array. If you need an ordered list, then use an Array. If you need fast random access or searching (by key), then use a Dictionary. Dictionaries can also be thought of like a Javascript JSON object (they are essentially the same idea) where you can hold a variety of different data types.

    Also, you can combine types. You can have a Array of Dictionaries, or a Dictionary that contains Arrays. Or a Dictionary of Dictionaries. It depends what you need.