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

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]

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

Substitute of "occursin" function to find a string in an Array{String,1}

What I am trying to do is
i = occursin("ENTITIES\n", lines)
i != 0 || error("ENTITIES section not found")
The error information is
ERROR: LoadError: LoadError: MethodError: no method matching occursin(::String, ::Array{String,1})
Closest candidates are:
occursin(::Union{AbstractChar, AbstractString}, ::AbstractString) at strings/search.jl:452
This is a piece of julia v0.6 code. I am using v1.1 now. I am new to julia and don't know what's the proper subsititute function for this. Please help.
You can broadcast orrursin like this (add a . after function name):
julia> x = "abc"
"abc"
julia> y = ["abc", "xyz"]
2-element Array{String,1}:
"abc"
"xyz"
julia> b = occursin.(x, y)
2-element BitArray{1}:
true
false
julia> findall(b)
1-element Array{Int64,1}:
1
julia> findfirst(b)
1
Note that although String can be iterated over it is treated by broadcast as a scalar.
Also it is worth to remember that occursin returns Bool value so that you can use it directly in logical tests e.g. i || error("ENTITIES section not found") in the code from your question.
In order to locate the index in the collection of the occurrence of true in the return value of broadcasted occursin use findall or findfirst functions (there is also findlast). The difference is that findall returns a vector of entries where true is encountered in the collection, while findfirst returns the first such entry only. Also note the difference when you pass all falses to it. findall will return an empty vector and findfirst will return nothing.
If you do not want to retain the vector b in the code above, you can get the indices directly (this should be faster) by passing a predicate as a first argument to findall/findfirst:
julia> findall(t -> occursin(x, t), y)
1-element Array{Int64,1}:
1
julia> findfirst(t -> occursin(x, t), y)
1

Julia 1.0.0: What does the `=>` operator do?

I see this Stackoverflow code for =>, but when I search Julia 1.0.0 on-line help for "=>", I get zero hits.
replace!(x, 0=>4) # The last expression is the focus of this question.
In the REPL help I get:
help?> =>
search: =>
Pair(x, y)
x => y
Construct a Pair object with type Pair{typeof(x), typeof(y)}. The elements are stored in the fields first and second.
They can also be accessed via iteration.
See also: Dict
Examples
≡≡≡≡≡≡≡≡≡≡
julia> p = "foo" => 7
"foo" => 7
julia> typeof(p)
Pair{String,Int64}
julia> p.first
"foo"
julia> for x in p
println(x)
end
foo
7
What does => do in replace!(x, 0=>4)? Does it create a pair, a replacement of all zeros by fours, or what? Why do I seem to not find it in the Julia 1.0.0 on-line docs?
EDIT
Code added to help me understand #Bill's helpful answer below:
julia> x = [1, 0, 3, 2, 0]
5-element Array{Int64,1}:
1
0
3
2
0
julia> replace!(x, 0=>4)
5-element Array{Int64,1}:
1
4
3
2
4
Edit 2
Besides #Bill's accepted answer, I found #Steven's answer helpful as well. Sorry I could not check them both, but Bill's came in first and they both offered useful information.
"What does => do in replace!(x, 0=>4)? Does it create a pair, a replacement of all zeros by fours, or what?"
It creates a Pair. In the function replace, a Pair in the second argument position means the multiple dispatch of replace() chooses a version of the replace function where, given a numeric array or string x, all items within x fitting the first part of the Pair are replaced with an instance of the second part of the Pair.
You can check the REPL docs for replace for details.
This small example should show how "=>" makes a pair
julia> replace("julia", Pair("u", "o"))
"jolia"
julia> replace("julia", "u" => "o")
"jolia"
"=>" operator means "Change into"
so
julia> replace("hello world",'l' => 'z')
"hezzo worzd"
means Change the string "hello world" using "change" 'l' "into" 'z'
and producing the resultant string "hezzo worzd"
julia> replace( [1,2,3,4,5], 3 => 666 )
5-element Array{Int64,1}:
1
2
666
4
5

How to pass Dict as the argument to method Julia

Hello i trying create converter method from Disct to Vector in Julia language.
But i receive error, with i can't understand
ERROR: TypeError: Tuple: in parameter, expected Type{T}, got Dict{AbstractString,Int64}
My code
type Family
name::UTF8String
value::Int
end
function convertToVector(a1::Dict{AbstractString, Int64}())
A::Vector{Node}
for k in sort(collect(keys(a1)))
push!(A, Family(a1[k] , k))
end
return A
end
Any idea hot to change convertToVector method ?
There were several typos in the above code, but I think this should work:
# No () after the type of a1
# Also, see comment, better to parameterize function, use concrete type for Dict
function convertToVector{T<:AbstractString}(a1::Dict{T, Int64})
# This is how you create an empty vector to hold Family objects
A = Vector{Family}()
for k in sort(collect(keys(a1)))
# The values passed to the Family constructor were backwards
push!(A, Family(k, a1[k]))
end
A
end
Another way (probably not very quick):
julia> dict = Dict("fred" => 3, "jim" => 4)
Dict{ASCIIString,Int64} with 2 entries:
"fred" => 3
"jim" => 4
julia> Vector{Family}(map(f -> Family(f...), map(x -> collect(x), dict)))
2-element Array{Family,1}:
Family("fred",3)
Family("jim",4)
Perhaps I've been using too much Lisp recently...

Julia : construct Dictionary with tuple values

Is there a possibility to construct dictionary with tuple values in Julia?
I tried
dict = Dict{Int64, (Int64, Int64)}()
dict = Dict{Int64, Tuple(Int64, Int64)}()
I also tried inserting tuple values but I was able to change them after so they were not tuples.
Any idea?
Edit:
parallel_check = Dict{Any, (Any, Any)}()
for i in 1:10
dict[i] = (i+41, i+41)
end
dict[1][2] = 1 # not able to change this way, setindex error!
dict[1] = (3, 5) # this is acceptable. why?
The syntax for tuple types (i.e. the types of tuples) changed from (Int64,Int64) in version 0.3 and earlier to Tuple{Int64,Int64} in 0.4. Note the curly braces, not parens around Int64,Int64. You can also discover this at the REPL by applying the typeof function to an example tuple:
julia> typeof((1,2))
Tuple{Int64,Int64}
So you can construct the dictionary you want like this:
julia> dict = Dict{Int64,Tuple{Int64,Int64}}()
Dict{Int64,Tuple{Int64,Int64}} with 0 entries
julia> dict[1] = (2,3)
(2,3)
julia> dict[2.0] = (3.0,4)
(3.0,4)
julia> dict
Dict{Int64,Tuple{Int64,Int64}} with 2 entries:
2 => (3,4)
1 => (2,3)
The other part of your question is unrelated, but I'll answer it here anyway: tuples are immutable – you cannot change one of the elements in a tuple. Dictionaries, on the other hand are mutable, so you can assign an entirely new tuple value to a slot in a dictionary. In other words, when you write dict[1] = (3,5) you are assigning into dict, which is ok, but when you write dict[1][2] = 1 you are assigning into the tuple at position 1 in dict which is not ok.

Check if an Object is an Array or a Dict

I'd like to check if var is an Array or a Dict.
typeof(var) == Dict
typeof(var) == Array
But it doesn't work because typeof is too precise: Dict{ASCIIString,Int64}.
What's the best way ?
If you need a "less precise" check, you may want to consider using the isa() function, like this:
julia> d = Dict([("A", 1), ("B", 2)])
julia> isa(d, Dict)
true
julia> isa(d, Array)
false
julia> a = rand(1,2,3);
julia> isa(a, Dict)
false
julia> isa(a, Array)
true
The isa() function could then be used in control flow constructs, like this:
julia> if isa(d, Dict)
println("I'm a dictionary!")
end
I'm a dictionary!
julia> if isa(a, Array)
println("I'm an array!")
end
I'm an array!
Note: Tested with Julia 0.4.3
Instead of checking for a particular concrete type, such as Array, or Dict, you might do better by checking for the abstract types, and gain a lot of flexibility.
For example:
julia> x = [1,2,3]
3-element Array{Int64,1}:
1
2
3
julia> d = Dict(:a=>1,:b=>2)
Dict(:a=>1,:b=>2)
julia> isa(d, Associative)
true
julia> isa(x, AbstractArray)
true
There are many different types of arrays in Julia, so checking for Array is likely to be too restrictive, you won't get sparse matrices, for example.
There are also a number of different types of associative structures, Dict, ObjectIdDict, SortedDict, OrderedDict.

Resources