Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I sort a dictionary and is that possible?

So let's imagine a dictionary which has these values in it:

Items = {
	["Item1"] = 50,
	["Item2"] = 200,
	["Item3"] = 100
{

Assuming this is a shop and we want sort it by price, we would want it to look like this:

Items = {
	["Item1"] = 50,
	["Item3"] = 100,
	["Item2"] = 200
{

But now the question is, how would we sort it using coding? Because I have been trying to figure it out for quite a long time now and so far, nothing has worked.

Can anyone help me?

1 comment

0

Sorting a dictionary inherently doesn't make any sense, due to the way they're stored in memory. https://scriptinghelpers.org/questions/60697/why-does-the-table-not-printing-in-logical-order#59068 for an explanation.

2 answers

✓ Accepted answer

As dictionary keys are not integers, they cannot be sorted. Arrays, however, have integer keys, giving them an order. So, there are multiple ways of ordering your item table:

1. Get rid of item name:

If the item name isn't required, you can simply do this:

Items = {
    50,
    200,
    100
}

Which will give a sorted table when you iterate through it.

2. Have your item details in dictionaries in an array:

If you're item names do matter, you could instead do this:

Items = {
	{
		Name = "Item1",
		Price = 50
	},
	{
		Name = "Item2",
		Price = 200
	},
	{
		Name = "Item3"
		Price = 100
	}
}

To iterate throgh this table, you can then do:

for _,Item in pairs(Items) do
	print(Item.Name, Item.Price)
end

which would print them in order.

3. Use two tables:

Alternatively, you could have one dictionary for the item details and one dictionary for the names:

ItemDetails = {
    ["Item1"] = 50,
    ["Item2"] = 200,
    ["Item3"] = 100
}

local Items = {"Item1","Item2","Item3"}

You could then iterate through this by going:

for _,ItemName in pairs(Items) do
	local ItemPrice = ItemDetails[ItemName]
	print(ItemPrice)
end

Which will print it in the order of the Items table, however you have to enter each item name twice.

Hope this helps!

Keys are not ordered in a dictionary, so you cannot sort it. Consider using an array.

This discussion is preserved as it was. New answers, comments, and votes are closed.