Is there a way to preserve order of keys when storing a dictionary in ConfigFile?

Godot Version

4.3.stable

Question

When storing a dictionary in a ConfigFile and saving it to disk, all the keys within the dictionary get resorted in alphabetical order. However, I would like the order to be preserved as it is set up in the original dictionary (without having to store each value one by one). Is there any way to prevent it from changing the order?

Why would you need the order to be the same? If you need a specific order, use an Array instead. Dictionary isn’t really meant to be iterated on, but rather values accessed directly by the key - the order then doesn’t matter.

For one, the reason I want to use a ConfigFile in the first place is to have it directly editable, and for that I’d like to have the variables laid out in a sensible manner to make it more readable.

But I’ve also got some data for which I need the capabilities of both dictionaries and arrays, and while it’s easy to convert parts of a dictionary into an array with .keys() or .values() whenever needed, you can’t really do that in reverse.

If you need to preserve the specific order, I believe you need to use an Array. You could mimic the Dictionary by having two Arrays: one for keys and one for values. Or you can have a Dictionary where keys are ordered integers 1, 2, 3… and the values are a tuple-like Array consisting of a named key and a value.

1 Like

You can’t order keys of a dictionary. it is not possible in any programming language, atleast the ones I know.
Dictionary is only a key-value relationship. To keep order of any group of elements use array.
You can keep your dictionary and have another array that records the order of keys.

1 Like

Thanks for the suggestions, everyone!

What I ended up doing is iterate through the dictionary using .keys() and .values() to store each value from the dictionary in the file separately (I’ve got some nested dictionaries in there too, but luckily only to a depth of 1, so I could just make separate sections for each sub-dictionary in the config), then on loading do the reverse by parsing the file with get_sections and get_section_keys to rebuild the dictionary in order.

You are still at the mercy of the underlying code for storing dictionaries while in memory.
Does GDScript guarantee dictionary order?
Not every language does, however, I believe that GDScript does in fact maintain the order of elements.

I agree with the other posters. The dictionary structure is not meant to rely on order. A dictionary is often defined as an unordered list (although iterating a dict is not uncommon).
You got it working and that’s good but less than ideal.