4
$\begingroup$

I have a list

list = {"a","b","c",…}

and I want the association

<| 1 -> "a", 2 -> "b", 3 -> "c", … |>

This seems like the sort of thing there would be a built-in function for, but I haven't been able to find one.

I could do this using

list // AssociationThread[Range @ Length[#], #] &

or

Association@MapIndexed[First[#2] -> #1 &, list]

or

AssociationMap[list[[#]]&, Range @ Length[list]]

but these are all rather unwieldy. Is there a better way?

$\endgroup$
4
  • 3
    $\begingroup$ I don't think that there is a better way. These seem quite simple to me. AssociationThread[Range@Length[list] -> list] is likely the fastest. $\endgroup$
    – Szabolcs
    Jan 11, 2017 at 11:34
  • $\begingroup$ I keep a shorthand for Range@*Length because I use it so often; that would at least shorten your code. $\endgroup$
    – Mr.Wizard
    Jan 11, 2017 at 12:02
  • $\begingroup$ @Mr.Wizard - In this case, Range@Length@list is one character shorter than Range@*Length@list $\endgroup$
    – Bob Hanlon
    Jan 11, 2017 at 13:55
  • $\begingroup$ @Stephan Powell For nested lists you could do l = {"a", {"b", "c"}}; a = <||>; MapIndexed[AssociateTo[a, #2 -> #1] &, l, {-1}]; $\endgroup$
    – M.R.
    Jan 11, 2017 at 16:29

0

Your Answer

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

Browse other questions tagged or ask your own question.