Is there a way to preserve the entered order of Keys in a Dictionary

I set up a dictionary by first creating a JSON string with Keys, Values in a particular order.
Then I use For Each Key in Dictionary to get a list of Keys out... this list is always in alphabetical order, however I would like to be able to keep the original order (as in the JSON string).

The only way I can think of to do this is to have the keys as 01key1, 02key2 etc and then strip out the leading digits after the list is created. However that seems very cumbersome and would mean remembering the appropriate digits for the key for later use, which kind of defeats the whole point of a lookup.

Is there another way of accomplishing this?

Working directly with the JSON is one option:

For each in order of JSON keys .kmmacros (2.4 KB)

Thank you ComplexPoint

I followed your example but the output I got was

${k} → ${dict[k]}
${k} → ${dict[k]}
${k} → ${dict[k]}
${k} → ${dict[k]}
...

So I suspect I misunderstood where to substitute something for a variable.

However, while working through this I had an AHA moment (more like well DUH actually). Since my keys are in the order I want in the JSON string, then I can simple collect the list from there and then set up the dictionary, rather than try and recreate it from the dictionary.

So you taught me something new and got my brain to work in one go... thank you!

Perhaps your code was missing the pair of backticks ?
(or used quote characters in their place ?)

`${k} → ${dict[k]}`
Expand disclosure triangle to view JS source
const dict = JSON.parse(kmvar.local_JSON)

return Object.keys(dict).map(
	k => `${k} → ${dict[k]}`
)
.join("\n")

In any case – it sounds like a solution has emerged :slight_smile:

You are correct... I had used single quotes instead of back ticks... so thanks again

Dave

:+1:

1 Like