# generate association based on list

a is a list {1,2,3,4}

b is an association <|1->a, 2->b, 3->c, 4->d|>

I am trying to write a single line of code to get b from a

b=<|#->myFunction[#] &|> /@ a

Here is the output:

Association[#1->myFunction[#1]&][1]

Can someone help find out a correct way to do it?

btw, I can do it using for loop, of course, just trying to see if I can use only one line to do it :-)

• Try b = <|# -> myFunction[#]|> & /@ a do not use () for function parameters Mathematica uses [] Apr 29, 2017 at 14:14
• Also try a = Range[4]; b = CharacterRange["a", "d"]; Association@((#[[1]] -> #[[2]] &) /@ Transpose[{a, b}]) Apr 29, 2017 at 14:28
• @VahagnTumanyan I did use [#] in my code, just a typo in my original post, now just corrected it. Apr 29, 2017 at 16:13

Just found a function AssociationMap

listOfKeys = {key1, key2, ...};

AssociationMap[f, listOfKeys]
->  <|key1->f[key1], key2->f[key2], ...|>

• xs = Range[4]; Association @@ Map[Rule[#, f[#]] &]@xs Apr 29, 2017 at 18:31
• @tomd just realized you had done it before me :) there is also a function AssociationThread that merges what you just did. Apr 29, 2017 at 18:51
AssociationThread[# -> FromLetterNumber[#]] &@Range[4]

• This is what I was trying to do :-) (Variant: AssociationMap[FromLetterNumber, a]). Apr 29, 2017 at 18:54
• @tomd thanks ! yours is more compact. Apr 29, 2017 at 19:03