How to sort a Dictionary in order?

Hello,
I am currently writing a modulescript that holds a Table of Dictionaries of purchasable hats for my game. The dictionaries include the price of the hat and I want to place the buttons to buy the specified hats into a GuiList in the PlayerGui from lowest price to highest price. However, obviously ipairs doesn’t work with dictionaries so I’m a little stuck on how I would go about doing this.

Here’s an example of the Table:
image

I was able to use normal pairs to place all the buttons into the Gui so that isn’t the problem, I just need them placed in order by price. Any help is appreciated.

“pairs()” is basically Ipairs but for dictionarys, same formatting as Ipairs. Example:

local dictionary = { hi = 1, go = 4 }

for key, value in pairs(dictionary) do
print(key, value)
end

Take a look at table.sort in the API documentation. You can specify a custom sort function.

1 Like

You can use table.sort to organise based on the price.

For example:

local hats = {
	hat_tophat = {
		price = 2
	},
	
	hat_glasses = {
		price = 1
	}
}

table.sort(hats, function(a,b)
	return a["price"] < b["price"]
end)


for i, v in pairs(hats) do
	print(v["price"])
end
1 Like

I’m still a little confused because I am not familiar with table.sort, it seems to have only put them in order when they’re out of order in the first place when I tried it. For example,

local hats = {
	hat_tophat = {
		price = 2
	},
	
	hat_glasses = {
		price = 1
	}
}

…would result in a print of “1,2”, however

local hats = {
	hat_glasses = {
		price = 1
	},
	
	hat_tophat = {
		price = 2
	}
}

…would result in a print of “2,1”. That, and I don’t know how to make this work for a long list of hats as well

Sorry for the confusion, that function only works on arrays. In this case you would have to add all of the dictionary prices into an array and sort it from there:

local hats = {
	hat_tophat = {
		price = 2
	},
	
	hat_glasses = {
		price = 100
	},
	
	hat_other = {
		price = 20
	},
	
	hat_scarf = {
		price = 1
	}
}

local array = {}
for key, value in pairs(hats) do
	array[#array+1] = {value = value["price"]}
end

table.sort(array, function(a, b)
	return a.value < b.value
end)

for i, v in ipairs(array) do
	for i, v in pairs(v) do
		print(v)
	end
end

Hope that helps. :slight_smile:

3 Likes

Many thanks! This does work, however I was wondering if there’s a way I can keep the name of the hat (which was the key for the values in the Dictionary table) as the Index in the Array table?

Absolutely, just change:

local array = {}
for key, value in pairs(hats) do
	array[#array + 1] = {key = key, value = value["price"]}
end
1 Like

Oh cool, I tried to do that a similar but different way and it resulted in an error lol. Thank you :]