dict remove also deletes key

Tcl’s dict remove does not behave exactly as I expected. (I'm sure it's because my expectations are incorrect)

% set d [dict create]
% dict set d O1 C1 child1
O1 {C1 child1}
% dict set d O1 C2 child2
O1 {C1 child1 C2 child2}
% dict set d O2 C3 child3
O1 {C1 child1 C2 child2} O2 {C3 child3}
% dict remove $d O1 C1
O2 {C3 child3}

I was expecting the result to be:

O1 {C2 child2} O2 {C3 child3}

What's the reason for O1 C2 also being removed?

1 answer

  • answered 2018-11-08 06:54 Jerry

    You are probably looking for dict unset instead of dict remove.

    dict unset will remove a key (and nested keys) with the value(s) associated to the deepest key.

    % dict unset d O1 C1
    O1 {C2 child2} O2 {C3 child3}
    

    dict remove will remove all the keys at the first level of the dictionary and all the values under those keys:

    % puts $d
    O1 {C1 child1 C2 child2} O2 {C3 child3}
    % dict set d O3 C4 child4
    O1 {C1 child1 C2 child2} O2 {C3 child3} O3 {C4 child4}
    % dict remove $d O1 O2
    O3 {C4 child4}