Pushing values to dic

I’ve the below code:

dict = Dict{Int64, Vector{Float64}}()

files = filter(x->endswith(x, ".pdf"), readdir())
for (i, f) in enumerate(files)
       push!(dict[i], f)
end

But I got the below error:

KeyError: key 5 not found

Stacktrace:
 [1] getindex(::Dict{Int64,Array{Float64,1}}, ::Int64) at .\dict.jl:477
 [2] top-level scope at .\In[16]:21

The dictionary is empty, which is why dict[5] says that no such key exists. You probably want dict[i] = [f] instead, that way a new array is assigned there.

1 Like

Alternatively, you can push a key-value pair:

push!(dict, i => f)

Personally, I’d prefer @Sukera’s answer though.

1 Like

Thanks, I thought it is managed the same way of Array

Your code wouldn’t work for an array either.

mmm, it worked for this one:

found_skills = []
for (i, entry) in enumerate(found)
      push!(found_skills, entry.match)
end

This is not the code you had for Dict

You had

If you actually treat the Dict as a collection and want to push to it though, it should work.

Also, the question is what do you want to push in. Did you want an array of file names stored as value in the dict (i.e. [f]) or do you want to store the fiile name itself. Your initialization of the dict doesn’t match any of these.

1 Like

Thanks, your answer made it clear for me.