I'm trying to extract values from list of tuples:
s3_headers = %{headers: [{"x-amz-id-2","yQKurzVIApkxxxxxxxxxxxxxxxxxxxxxxxxxxxxxFBINsPxe+7Vc="},
{"x-amz-request-id", "82xxxxxxxxx23"},
{"Date", "Thu, 25 May 2017 22:03:09 GMT"},
{"Last-Modified", "Thu, 25 May 2017 21:42:28 GMT"},
{"ETag", "\"6f04733333333333333368997\""},
{"x-amz-meta-original_name", "Screenshot from 2016-11-27 17-32-03.png"},
{"Accept-Ranges", "bytes"}, {"Content-Type", ""},
{"Content-Length", "612391"}, {"Server", "AmazonS3"}], status_code: 200}
The way how I manage to do it so far is like this:
{"x-amz-meta-original_name", original_name } = s3_headers |> List.keyfind("x-amz-meta-original_name", 0)
{"Content-Length", content_length } = s3_headers |> List.keyfind("Content-Length", 0)
{"Content-Type", content_length } = s3_headers |> List.keyfind("Content-Type", 0)
It feels like overcomplication can you recommend better way ?
Keyword.get
used to work for this but I just checked it only works for atom keys. I don't think there's any better way to find an item in a list of tuples. You can create a map from this and use pattern matching or bracket notation but I'd just create a wrapper forList.keyfind
which returns only the found value. See github.com/elixir-lang/elixir/blob/….Enum
'sfind
, eg:{"x-amz-meta-original_name", original_name} = Enum.find(s3_headers, fn {key, _val} -> key == "x-amz-meta-original_name" end)
.