Organinizing values into order od highest to lowest

Godot Version

4.2

Question

Hello! I need help with organizing dictionary values into list. So I have in example this kind of dict var parties = {party1 = 12, party2 = 84, party3 = 4} and I want to print them in order of highest to lowest which would look like this ”party2, party1, party3”

Hi there. I will structure the code like this so it is easier to understand…

extends Node2D

func _ready():
    # Your dictionary parties
	var parties = {
		"party1": 12,
		"party2": 84,
		"party3": 4,
		"party4": 14,
		"party5": 2,
	}
	
	# Using a lambda function to make it more cleanish
	# parties.keys() returns the keys in the dictionary
	# Note that you could put this in a method and then return the sorted parties

	var sorted_parties = parties.keys()
	sorted_parties.sort_custom(func(a,b): # <- lambda function.
		return parties[b] < parties[a]
		# character ">" would be ascending, "<" is descending
	)

	# Print the sorted array
	# Result: party 2, 4, 1, 3, 5
	print(sorted_parties)

This should do the trick :slight_smile:

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.