How to get the name of a dictionary value

Hello:

Dictonary:

local myDic = { -- my dic lol
["dic1"] = "dic", 
["dic2"] = "dic"
}

Retrieve value

myDic["dic1"]

Retrieve name

???? -- how to do this?!?!?!?!
1 Like
table.find(myDictionary, "Dictionary1")
-- First parameter is the table
-- Second parameter is the value
-- Will output the key aka the "name"
1 Like

Isn’t that for arrays though? table.find even specifies an index, i.e., it assumes numerical keys.

1 Like

Can confirm, table.find is INVALIDATED for dictonary instances.

local myBigDic = {
["dic1"] = "hello"
}


 print(table.find(myBigDic, "dic1")) -- nil
1 Like

In that case, one can consider this

local findValue = "ADictionaryValue"
local foundKey
for k, v in pairs(myDictionary)
    if v == findValue then
        foundKey = k -- Depends on if you want it to return
    end
end
1 Like

What if i did something like “reversed” the values like this:

local reverseDic = {}

local BigBigDic = {
    ["dic1"] = "dic value"
}

for itemName, itemValue in pairs(BigBigDic) do
    reverseDic[itemValue] = itemName  -- Fixed variable names v and i
end

print(reverseDic["dic value"])  -- Corrected indexing, using the actual value

1 Like

The problem here is that table.find() is suited to find the value and not access the value through key which is what you’re trying to do. Although even if you did it correct, it will still not work due to gap between dictionary and array as pointed out by @PhoenixRessusection

There’s nothing stopping you from doing that.

local function swapKeysAndValues<K, V>(dictionary: { [K]: V }): { [V]: K }
    local swapped = {}

    for key, value in pairs(dictionary) do
        swapped[value] = key
    end

    return swapped
end
1 Like

This is my resolution
It must be the solution
a clear constitution
My Seeking answers
ends with my own contribution

4 Likes

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