1
$\begingroup$

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 :-)

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

2 Answers 2

2
$\begingroup$

Just found a function AssociationMap

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

AssociationMap[f, listOfKeys] 
->  <|key1->f[key1], key2->f[key2], ...|>
$\endgroup$
2
  • $\begingroup$ xs = Range[4]; Association @@ Map[Rule[#, f[#]] &]@xs $\endgroup$
    – webcpu
    Apr 29, 2017 at 18:31
  • $\begingroup$ @tomd just realized you had done it before me :) there is also a function AssociationThread that merges what you just did. $\endgroup$
    – Ali Hashmi
    Apr 29, 2017 at 18:51
2
$\begingroup$
AssociationThread[# -> FromLetterNumber[#]] &@Range[4]
$\endgroup$
2
  • 1
    $\begingroup$ This is what I was trying to do :-) (Variant: AssociationMap[FromLetterNumber, a]). $\endgroup$
    – user1066
    Apr 29, 2017 at 18:54
  • $\begingroup$ @tomd thanks ! yours is more compact. $\endgroup$
    – Ali Hashmi
    Apr 29, 2017 at 19:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.