How do you sort items in a dictionary according to Number?

Hello,
let’s say you have a dictionary as follows :

19 = Nineteen
12 = Twelve
22 = Twenty-Two

How would you sort it so that when it is iterated, it is sorted from Highest to Lowest Key Number?

1 Like
table.sort(dict)

This will automatically sort your table based on its indices. So no extra work here on your part.

Ordered iteration through a dictionary is never guaranteed so attempting to apply a sort to it is pointless. You’ll need to create a proxy array for this containing all the keys of the dictionary and sort that array. Then when you’re performing iteration, you do it over the array and from whatever value is selected for the current iteration, perform a lookup against your dictionary.

local dictionary = {
    ["A"] = 1,
    ["B"] = 2,
    ["C"] = 3
}

local array = {}

for key, _ in pairs(dictionary) do
   table.insert(array, key)
end

table.sort(array --[[, compareFunction]])

for _, key in ipairs(array) do
    local valueForKey = dictionary[key]
end

This question’s been asked in the past before actually and this is the appropriate strategy for doing so. table.sort does not work on dictionaries, it is intended for arrays.

https://devforum.roblox.com/search?q=sort%20dictionary

This topic is also discussed in Programming in Lua, which is a book for Lua created by its developer, Roberto Ierusalimschy. See: 19.3 - Sort.

A common mistake is to try to order the indices of a table. In a table, the indices form a set, and have no order whatsoever. If you want to order them, you have to copy them to an array and then sort the array.

9 Likes

But wouldn’t it be listed as it is?

[1] 19 = Nineteen
[2] 12 = Twelve
[3] 22 = Twenty-Two

Let me try this out and see if it’s what I am looking for.

Thank you!

nvm was confused about what you were trying to do

Is this what you’re trying to do?

local t = {
["One"]=1,
["Two"]=2
}

local t2 = {};
for i,v in pairs(t) do
   table.insert(t2,v);
end

table.sort(t2);
t=t2;
1 Like

Nope, it’s fine now I think @colbert2677 helped me enough.

Thanks anyways though!