juliastructuremultiplication

Simple command to multiply all values of a dictionary by a float


In Julia, you can easily multiply all values of a Vector, Matrix or Array a by a Float64, say 2, by:

a=ones(3,3)
a*=2

I wanted to know if this is also easily achievable for dictionaries, for instance, Dictionary{Int,Float64} or Dictionary{Tuple{Int,Int},Float64}

I know it can be done by iterating with for loops on keys and values but I want to do it "in place" like dict*=2. Is it possible?


Solution

  • This in-place map! might be 20X faster than replace.

    map!(x->2x, values(d))
    

    Testing:

    julia> @benchmark map!(x->2x, values(d)) setup=(d = Dict(1:100 .=> rand(100)))
    BenchmarkTools.Trial: 10000 samples with 985 evaluations.
     Range (min … max):  59.391 ns … 154.315 ns  ┊ GC (min … max): 0.00% … 0.00%
     Time  (median):     60.508 ns               ┊ GC (median):    0.00%
     Time  (mean ± σ):   61.706 ns ±   4.912 ns  ┊ GC (mean ± σ):  0.00% ± 0.00%
    
       █
      ▃██▆▄▄▃▃▃▃▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▁▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂ ▂
      59.4 ns         Histogram: frequency by time         86.9 ns <
    
     Memory estimate: 0 bytes, allocs estimate: 0.
    

    vs.

    julia> @benchmark d_mult = replace(kv -> kv[1] => kv[2]*2, d) setup=(d = Dict(1:100 .=> rand(100)))
    BenchmarkTools.Trial: 10000 samples with 30 evaluations.
     Range (min … max):  916.667 ns … 274.520 μs  ┊ GC (min … max):  0.00% … 99.13%
     Time  (median):       1.153 μs               ┊ GC (median):     0.00%
     Time  (mean ± σ):     3.052 μs ±  11.919 μs  ┊ GC (mean ± σ):  21.27% ±  5.50%
    
      ▆█▅▄▁                  ▁▂▂▃▂▄▇▆▃▁                             ▂
      █████▇▇▆▄▄▁▁▄▁▄▅▅▃▃▁▃▁▁███████████▇▇▆▆▅▅▄▄▅▆▅▅▆▄▄▅▄▃▄▄▅▅▅▆▆▆█ █
      917 ns        Histogram: log(frequency) by time       7.68 μs <
    
     Memory estimate: 4.72 KiB, allocs estimate: 5.