Getkey for dictionaries with composite-typed values

Hi.
I’m intermediate level in Julia.

For some problem I want to solve, I have to define a custom composite type:

struct NodeData
    presence_cpu::AbstractVector{Bool}
    presence_gpu::AbstractVector{Bool}
    mem_allocation_cpu::Float64
    mem_allocation_gpu::Float64
    state::Int64
end

and I then create a dictionary with values of this custom type with dict_nodes = Dict{Int64,NodeData}()

As advised by the docs I created my own hash function for NodeData, which allows me to check is some NodeData element is in the dictionary.

But for some reason I need to get the key corresponding to a specific value of the dictionary.
I’m confused because it doesn’t work as shown by this minimal example:

dict_nodes
# returns:
Dict{Int64, NodeData} with 1 entry:
  0  => NodeData(Bool[1, 0, 0, 1, 0], Bool[0, 0, 0, 0, 0], 1100.0, 0.0, 0)

# then
el0 = NodeData(Bool[1, 0, 0, 1, 0], Bool[0, 0, 0, 0, 0], 1100.0, 0.0, 0)
el0 in values(dict_nodes)
# returns
true

# but  the command
getkey(dict_nodes, el0, nothing)
# returns nothing

I couldn’t find the solution to this anywhere.
Thanks in advance for some suggestions or help.

From Julia docs: getkey(collection, key, default) Return the key matching argument key if one exists in collection , otherwise return default.

The second argument of getkey is a key (for example, 0 in your dict_nodes), not a value. Also, you’re required to define hash() and isequal() for keys, not values. In your case the keys are integers not custom structs, so there’s nothing required from you.

1 Like