> Erlang中文手册 > erase/2 从字典里删除一个键

dict:erase/2

从字典里删除一个键

用法:

erase(Key, Dict1) -> Dict2

内部实现:

-spec erase(Key, Dict1) -> Dict2 when
      Key :: term(),
      Dict1 :: dict(),
      Dict2 :: dict().
%%  Erase all elements with key Key.

erase(Key, D0) -> 
    Slot = get_slot(D0, Key),
    {D1,Dc} = on_bucket(fun (B0) -> erase_key(Key, B0) end,
			D0, Slot),
    maybe_contract(D1, Dc).

erase_key(Key, [?kv(Key,_Val)|Bkt]) -> {Bkt,1};
erase_key(Key, [E|Bkt0]) ->
    {Bkt1,Dc} = erase_key(Key, Bkt0),
    {[E|Bkt1],Dc};
erase_key(_, []) -> {[],0}.

删除字典里跟键 Key 相关联的所有项

D = dict:from_list([{k1, v1}, {k2, v2}, {k3, v3}]),
dict:to_list(dict:erase(k1, D)).