how to get value from keyword list which key is integer?

Advertisements

The list is like [{0,10},{2,20}]. I have get value 10 when provided by key as 0.

I haven’t find the suitable function in Enum, List, Keyword module, and have to use erlang module proplists to solve the problem. Is it necessary?

inventory_position_list = [{0,10},{2,20}]
x = :proplists.get_value(0,inventory_position_list)

>Solution :

I believe List.keyfind/4 or List.keyfind!/3 are what you are looking for:

iex> List.keyfind!([{0,10},{2,20}], 2, 0)
{2, 20}

This returns the whole matching tuple though, so you’d need to pattern-match on the return:

{_, value} = List.keyfind!(list, key, 0)

Leave a ReplyCancel reply