# How can I get all pairs of values from an association with elements key->list

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?

• 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? – march Nov 11 '15 at 0:21

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]}

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