> Erlang中文手册 > fetch/2 在字典里查找值

dict:fetch/2

在字典里查找值

用法:

fetch(Key, Dict) -> Value

内部实现:

-spec fetch(Key, Dict) -> Value when
      Key :: term(),
      Dict :: dict(),
      Value :: term().

fetch(Key, D) ->
    Slot = get_slot(D, Key),
    Bkt = get_bucket(D, Slot),
    try fetch_val(Key, Bkt)
    catch
	badarg -> erlang:error(badarg, [Key, D])
    end.

fetch_val(K, [?kv(K,Val)|_]) -> Val;
fetch_val(K, [_|Bkt]) -> fetch_val(K, Bkt);
fetch_val(_, []) -> throw(badarg).

获取在字典 Dict 里跟键 Key 相关联的值

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

如果键 Key 不存在字典 Dict 里,则会抛出一个异常错误,例如以下这种情况

D = dict:from_list([{1, a}, {2, b}, {3, c}]),
case dict:fetch(4, D) of
    badarg ->
        not found;
    Value ->
        Value
end.