Ad
Log in to vote
3

How do I sort a dictionary and is that possible?

Asked by 2 years ago

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?

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. fredfishy 823 — 2y

2 answers

Log in to vote
3
Answered by
mattscy 3725 Moderation Voter Community Moderator
2 years ago
Edited 2 years ago

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!

Ad
Log in to vote
0
Answered by
Avigant 2374 Moderation Voter Community Moderator
2 years ago

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

Answer this question