Check if NDSparse key exists

If I have an NDSparse table, can I check if a key exists similar to dictionaries? With a dictionary (d) I can use haskey(d) but with a table (tab) haskey(tab) results in an error. I know I can do a try catch statement with tab[key1] but is there a more elegant and efficient way to check ahead of time if a key is available?

Are you using the latest version of IndexedTables? That should work since https://github.com/JuliaComputing/IndexedTables.jl/pull/215 .

julia> x = ndsparse(["a","b"], [3,4])
1-d NDSparse with 2 values (Int64):
1   β”‚
────┼──
"a" β”‚ 3
"b" β”‚ 4

julia> keys(x)
2-element StructArrays.StructArray{Tuple{String},1,NamedTuple{(:x1,),Tuple{Array{String,1}}}}:
 ("a",)
 ("b",)
julia> haskey(x, ("a",))
true

The tuple is important since the keys can be multi valued.

I’m using IndexedTables v0.12.0 but I didn’t install it myself. It is just the version that came with the latest JuliaDB. I don’t wanna mess up that installation. Is the branch you’re talking about what would be used by default?

this is what I get when I try that:

julia> x = ndsparse(["a", "b"], [3, 4])
1-d NDSparse with 2 values (Int64):
1   β”‚
────┼──
"a" β”‚ 3
"b" β”‚ 4

julia> keys(x)
2-element StructArrays.StructArray{Tuple{String},1,NamedTuple{(:x1,),Tuple{Array{String,1}}}}:
 ("a",)
 ("b",)

julia> haskey(x, "a")
ERROR: MethodError: no method matching haskey(::NDSparse{Int64,Tuple{String},StructArrays.StructArray{Tuple{String},1,NamedTuple{(:x1,),Tuple{Array{String,1}}}},Array{Int64,1}}, ::String)
Closest candidates are:
  haskey(::REPL.Terminals.TTYTerminal, ::Any) at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.1\REPL\src\Terminals.jl:174
  haskey(::LibGit2.CachedCredentials, ::Any) at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.1\LibGit2\src\types.jl:1274
  haskey(::Pkg.TOML.Table, ::AbstractString) at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.1\Pkg\ext\TOML\src\parser.jl:32
  ...
Stacktrace:
 [1] top-level scope at none:0

It needs to be ("a",) so it’s a tuple.

1 Like

Ah thank you.