I have an association of the form

ds=<|key1 -> list1, key2 -> list2,... ,keyn -> listn|>

I would like a simple way to map a function to all pairs {a, b}, where a is a key and b is element of the list associated with key a. I have found several brute-force methods but is seems that there should be something akin to

f /@ ds

This only feeds f with the lists one by one.

I can do it this way:

g[a_, b_] := h[a, #] & /@ b

Flatten@KeyValueMap[g, ds]

Is there a more compact way?

  • 1
    $\begingroup$ Please include your brute force methods! Especially if they do what you want! - that way, if we come up with what we think is a better solution, we can compare and make sure our results are correct. In addition, it's not clear what the output should be. Do you replace the Value with the output of the function? Do you replace the Key? Is the result just supposed to be a List of the computed values? $\endgroup$
    – march
    Nov 11, 2015 at 0:21

1 Answer 1



ds = <|key1 -> list1, key2 -> list2, keyn -> listn|>;

KeyValueMap[f] @ ds

$\ ${f[key1, list1], f[key2, list2], f[keyn, listn]}

ds = <|key1 -> {x1, y1}, key2 -> {x2, y2}, keyn -> {x3, y3}|>;

KeyValueMap[f[#1, #2[[1]]] &, ds]

$\ ${f[key1, x1], f[key2, x2], f[keyn, x3]}

  • 1
    $\begingroup$ This is close, what I need is f[key1,x1],f[key1,y1],f[key2,x2],f[key2,y2], etc. $\endgroup$
    – JJM
    Nov 11, 2015 at 0:56
  • 4
    $\begingroup$ @JJM in that case how about Flatten@KeyValueMap[Thread[f[##]] &, ds] or Flatten@KeyValueMap[f /* Thread, ds] $\endgroup$ Nov 11, 2015 at 1:21
  • $\begingroup$ @JJM "what I need is" - you really should edit your question to include that. $\endgroup$ Nov 11, 2015 at 1:28
  • $\begingroup$ @Mike Honeychurch Yes, this is what I was looking for. Thanks to you and Karsten 7 $\endgroup$
    – JJM
    Nov 11, 2015 at 1:31

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.