[erlang-questions] Processing a List into a Dict

Zoltan Lajos Kis <>
Mon Nov 30 22:24:05 CET 2009


Jarrod Roberson wrote:
> I have the following list
>
> ["txtvers=1","userid=3A6524D4-E31C-491D-94DD-555883B1600A","name=Jarrod
> Roberson","version=2"]
>
> I want to create a Dict where the left side of the = is the key and the
> right side is the value.
> Preferably where the key is an atom.
>
> Using the following list comprehension I get this.
>
>  KVL = [string:tokens(T,"=") || T <- TXT].
>
> [["txtvers","1"],
> ["userid","3A6524D4-E31C-491D-94DD-555883B1600A"], ["name","Jarrod
> Roberson"], ["version","2"]]
>
> what I am struggling with now is how to convert the nested lists into tuples
> so I can send them into a list of tuples
> where I can send them into dict:from_list
>
> what I want is something like this
>
> [{txtvers,"1"}, {userid,"3A6524D4-E31C-491D-94DD-555883B1600A"},
> {name,"Jarrod Roberson"}, {version,"2"}]
>
> I know there has to be a concise way to do this but I just can't get my head
> around it.
>
>   
KVL = [begin [K,V]=string:tokens(T,"="), {list_to_atom(K), V} end || T 
<- L].
If this feels ugly, you can move the begin-end part to a separate list.

If you only need this list for creating a dictionary, you can also foldl 
on your original list:

lists:foldl(fun(T, D) ->
                [K,V] = string:tokens(T, "="),
                dict:store(list_to_atom(K), V, D)
              end,
              dict:new(),
              L).

Regards,
oltan.



More information about the erlang-questions mailing list