Search code examples
dictionarymathluamax

Getting key with maximum value in dictionary? -In lua specifically


I've seen this question a few times for python but I am looking for how to do it in Lua. I have a dictionary that looks like:

myValues = {
"key1":123,
"key2":43,
"key3":367, 
"key4":2
}

I want a function or method that gives me the key with the largest value. In this case I would input the 'myValues' dictionary and it will throw out 'key3' as a result. Any ideas?


Solution

  • Lua table syntax isn't JSON. As a Lua table, this would be

    tab = {key1 = 123, key2 = 43, key3 = 367, key4 = 2}
    

    To find the key corresponding to the highest value, simply loop over the table:

    local max_key
    for key, value in pairs(tab) do
        if max_key == nil or value > tab[max_key] then
            max_key = key
        end
    end
    

    This can be rewritten to be slightly more elegant using next:

    local max_key = next(tab)
    for key, value in next, tab, max_key do
        if value > tab[max_key] then
            max_key = key
        end
    end
    

    For performance, you might want to keep the corresponding max. value in a local variable:

    local max_key, max_value = next(tab)
    for key, value in next, tab, max_key do
        if value > max_value then
            max_key, max_value = key, value
        end
    end