[erlang-questions] Processing a List into a Dict

Mihai Balea <>
Mon Nov 30 23:10:27 CET 2009


On Nov 30, 2009, at 4:22 PM, Jarrod Roberson wrote:

> Thanks for the responses, that got me on the right track, here is what I
> came up with.
> 
> TXT =
> ["txtvers=1","userid=3A6524D4-E31C-491D-94DD-555883B1600A","name=Jarrod
> Roberson","version=2"].
> 
> A = [ string:tokens(KV,"=") || KV <- TXT].
> [["txtvers","1"],["userid","3A6524D4-E31C-491D-94DD-555883B1600A"],["name","Jarrod
> Roberson"],["version","2"]]
> 
> D = [{list_to_atom(K),V} || [K|[V|_]] <- A].
> [{txtvers,"1"},{userid,"3A6524D4-E31C-491D-94DD-555883B1600A"},{name,"Jarrod
> Roberson"},{version,"2"}]
> 
> DT = dict:from_list(D).
> {dict,4,16,16,8,80,48,
>      {[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
>      {{[],[],[],
>        [[txtvers,49]],
>        [[userid,51,65,54,53,50,52,68,52,45,69,51,49|...]],
>        [[name,74,97,114,114,111,100,32,82,111,98,101|...]],
>        [],[],[],[],[],[],[],[],
>        [[version,50]],
>        []}}}
> 
> dict:find(name,DT).
> {ok,"Jarrod Roberson"}
> 
> this gets me the keys as atoms instead of "strings"

list_to_atom/1 is not something you want to use lightly. The reason is that atom space is not garbage collected, so this is a recipe for out of memory conditions if your application is long running and/or processes a lot of data. 

If you really need them as atoms and the set of things you want to convert is limited and known beforehand you might want to look into list_to_existing_atom/1

Mihai




More information about the erlang-questions mailing list