Skip to content

Get dict value as a nullable #13055

Open
Open
@dbeach24

Description

@dbeach24

I need a good way to both test for a value in a dictionary and get that value, without resorting to one of the following fallbacks, all of which are somewhat undesirable:

  1. get(dict, key, specialnullval) -- problematic because I must either use a separate type to represent null (inefficient due to the type-variadic return), or I must have some special way to represent null within the value type of the dictionary.
  2. haskey(dict, key) followed by dict[key] -- problematic because it looks up the key twice when it exists.
  3. try k = dict[key] catch ... -- problematic because it relies on exceptions when the key is not present.

It seems that all of this can be solved my making use of Julia v0.4's Nullable type, with something like the following:

function getnull{K,V}(h::Dict{K,V}, key)
    index = ht_keyindex(h, key)
    return (index<0) ? Nullable{V}() : Nullable{V}(h.vals[index]::V)
end

I am proposing that this be included as part of base/dict.jl, possibly under a different/better name.

Is there some other/better way to do this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    missing dataBase.missing and related functionality

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions