Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia DefaultDict uses the same value (array) for each key

I want to create a defaultdict of arrays. Problem is, it uses the same array for each key.

# using Pkg
# Pkg.add("DataStructures")
using DataStructures: DefaultDict
genome = DefaultDict{Tuple{String, String}, Array{Int64, 1}}(Int64[])
push!(genome["chr1", "+"], 5)
# 1-element Array{Int64,1}:
# 5

push!(genome["chrX", "-"], 10)
# 2-element Array{Int64,1}:
#  5
# 10

I have tried feeding it a lambda to create a new array x -> Int64, but that just gave a type error.

like image 217
The Unfun Cat Avatar asked Oct 29 '25 17:10

The Unfun Cat


1 Answers

I don't know how to solve your problem using DefaultDict, but I think Julia's in-build dictionary structure offers a better solution. One can use

get!(collection, key, default)

to automatically give a default value where one hasn't been set already. The above code would be rewritten:

genome = Dict{Tuple{String, String}, Array{Int64, 1}}()
push!(get!(genome, ("chr1", "+"), Int64[]), 5)
# 1-element Array{Int64,1}:
# 5

push!(get!(genome, ("chrX", "-"), Int64[]), 10)
# 1-element Array{Int64,1}:
# 10
like image 84
hjab Avatar answered Oct 31 '25 11:10

hjab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!