Quantcast
Channel: First steps - JuliaLang
Viewing all articles
Browse latest Browse all 2795

Tell if a key is present in a dict

$
0
0

This is a very beginner question. I would like to check if a key exists in a dictionary.

julia> 1 in Dict(1=>'a', 2=>'b')
ERROR: AbstractDict collections only contain Pairs;
Either look for e.g. A=>B instead, or use the `keys` or `values`
function if you are looking for a key or value respectively.
Stacktrace:
 [1] error(::String) at ./error.jl:33
 [2] in(::Int64, ::Dict{Int64,Char}) at ./abstractdict.jl:28
 [3] top-level scope at REPL[9]:1

This makes sense, a dictionary contains Pairs and not keys.

I can do this:

julia> 1 in keys(Dict(1=>'a', 2=>'b'))
true

But I think keys() returns an iterator, and the in operator iterates over all keys until it finds the key. AFAIK iterators only support sequential iteration. Using a linear search to find a key in a hashmap is crazy.

So how can I tell if a key is present in a Dict?

15 posts - 10 participants

Read full topic


Viewing all articles
Browse latest Browse all 2795

Latest Images

Trending Articles



Latest Images