# @threads fails when interating over a dictionary

**URL:** <https://discourse.julialang.org/t/threads-fails-when-interating-over-a-dictionary/78249>\
**Category:** General Usage\
**Tags:** parallel, dictionary, threads\
**Created:** [March 22, 2022, 2:05am UTC](https://discourse.julialang.org/t/threads-fails-when-interating-over-a-dictionary/78249 "2022-03-22T02:05:41Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![evan-wehi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/evan-wehi/32/32692_2.png) [@evan-wehi](https://discourse.julialang.org/u/evan-wehi)\
**Post date:** [March 22, 2022, 2:05am UTC](https://discourse.julialang.org/t/threads-fails-when-interating-over-a-dictionary/78249/1 "2022-03-22T02:05:41Z")

</div>

Trying to parallelise over a dictionary iterator fails.

```julia
using Base.Threads

d = Dict("a" => 1, "b" => 2)

@threads for (k, v) in d
  println("$(k) => $(v)")
end

```

produces

```julia
ERROR: TaskFailedException
Stacktrace:
 [1] wait
   @ ./task.jl:334 [inlined]
 [2] threading_run(func::Function)
   @ Base.Threads ./threadingconstructs.jl:38
 [3] top-level scope
   @ ./threadingconstructs.jl:97

    nested task error: MethodError: no method matching firstindex(::Dict{String, Int64})
    Closest candidates are:
      firstindex(::Any, ::Any) at ~/Applications/Julia-1.7.app/Contents/Resources/julia/share/julia/base/abstractarray.jl:396
      firstindex(::AbstractChar) at ~/Applications/Julia-1.7.app/Contents/Resources/julia/share/julia/base/char.jl:200
      firstindex(::UnitRange) at ~/Applications/Julia-1.7.app/Contents/Resources/julia/share/julia/base/range.jl:646
      ...
    Stacktrace:
     [1] (::var"#3#threadsfor_fun#5"{Dict{String, Int64}})(onethread::Bool)
       @ Main ./threadingconstructs.jl:70
     [2] (::var"#3#threadsfor_fun#5"{Dict{String, Int64}})()
       @ Main ./threadingconstructs.jl:52

```

There are obvious workarounds but it was a bit surprising to me.

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [March 22, 2022, 3:04am UTC](https://discourse.julialang.org/t/threads-fails-when-interating-over-a-dictionary/78249/2 "2022-03-22T03:04:36Z")

</div>

> [@evan-wehi](#):
>
> ```julia
> no method matching firstindex(::Dict{String, Int64})
> Closest candidates are:
> 
> ```

this is because `@threads` loop needs fixed indexing space and dictionary doesn’t have one. you probably want to use `collect` here
