How to get the empty entries from a Dictionary in Julia?

Viewed 162

I have some dictionary I have defined which might have values that are empty. Is there a quick way to check to see if any of my key value pairs contain empty entries?

julia> a = Dict(1=>[1,2], 4=>[3,4], 6=>[])
Dict{Int64, Vector{T} where T} with 3 entries:
  4 => [3, 4]
  6 => Any[]
  1 => [1, 2]

3 Answers

You wanted a quick way thus I would recommend:

findall(isempty, a)

One possible concise solution it to use a comprehension and the isempty function which will check this for you as follows:

julia> [k for (k,v) in a if isempty(v)]
1-element Vector{Int64}:
 6
julia> filter(p->isempty(p.second), a)
Dict{Int64, Vector{T} where T} with 1 entry:
  6 => Any[]

filter takes a function as its first argument and can take a Dictionary as its second argument.

The function is given a Pair of key-value pairs, which has members first (the key) and second (the value). So here, we filter by an anonymous function that checks whether p.second, i.e. the value, isempty, and return only those Pairs where that returns true.

An equivalent, and perhaps better looking, way to do this is:

julia> filter(isempty∘last, a)
Dict{Int64, Vector{T} where T} with 1 entry:
  6 => Any[]

And for completeness' sake, if you want to just "check to see if" any of them are empty, you can take a count instead:

if count(isempty∘last, a) > 0
    dosomething()
end
Related