Julia, weird behavior when changing keys during iteration through a dictionary

I experienced (in my opinion) strange behavior, repeating the dictionary of Julia and sorting out the key names during the iteration. The following example works as expected:

a = Dict("klaus_one" => 3,
         "bernd_one" => 5,
         "gabi_one" => 8)

for i= keys(a)
     x = pop!(a,i)
     a[join([i,"new"],"_")] = x + 3
end

Returns (as expected)

# Dict{ASCIIString,Int64} with 3 entries:
#   "gabi_one_new"  => 11
#   "bernd_one_new" => 8
#   "klaus_one_new" => 6

However:

a = Dict("klaus_one" => 3,
         "bernd_one" => 5,
         "gabi_one" => 8)

for i=1:5

    if i!=1

        # _keys = deepcopy(keys(a))
        _keys = keys(a)
        for k = _keys
            k_base = join(split(k,"_")[1:2],"_")
            a[k_base] = pop!(a,k) + 3 
        end
    end
    # _keys = deepcopy(keys(a))
     _keys = keys(a)

    for k = _keys
        k_new = join([k,"new2"],"_")
        a[k_new] = pop!(a,k) 
    end
end 

Results in:

# Dict{ASCIIString,Int64} with 3 entries:
#   "klaus_one_new2"      => 27
#   "gabi_one_new2"       => 32
#   "bernd_one_new2_new2" => 17

As the values ​​and the key "bernd_one_new2_new2" show, more than three iterations occur (although the dictionary has a length of 3). However, the “strange” behavior can be cured by deep copying the keys into a new object.

Is the behavior expected?

Thanks in advance!

(By the way, I'm using Julia Version 0.4.6 (2016-06-19 17:16 UTC))

+3
source share
1 answer

: . : ; , .

+6

Source: https://habr.com/ru/post/1650681/


All Articles