erlang

Extract all values from Erlang orddic


fetch_keys(Orddict)

Returns a list of all keys in a dictionary. So, how to return all values from dictionary whatever the keys are? I visited the documentation site and it seems there is no such function to fit my need. Then, how do it in custom function? Something like:

fetch_values(Orddict)

or

values2list(Orddict)

Solution

  • There doesn't seem to be a direct way to get all the values. You can convert the orddict to a list of key-value tuples using orddict:to_list/1 and then map over it using lists:map/2 to extract the value:

    1> D = orddict:from_list([{a, 1}, {b, 2}]).
    [{a,1},{b,2}]
    2> lists:map(fun ({_K, V}) -> V end, orddict:to_list(D)).
    [1,2]
    

    or using list comprehension:

    3> [V || {_K, V} <- orddict:to_list(D)].
    [1,2]