# Indexed KeyValueMap

I have been trying to figure it out and I am probably very close, but I have spent 2 hours without sucess. I have the expression below

MapIndexed[
geg[First[#2],
Total[KeyValueMap[fef[#1, #2, mem] &, #1]]] &, {<|a -> b,
c -> d|>, <|e -> f|>}]


which produces

{geg[1, fef[a, b, mem] + fef[c, d, mem]], geg[2, fef[e, f, mem]]}


I want to have the position of the association in the list {<|a -> b, c -> d|>, <|e -> f|>} passed both to geg and fef

That is, I want the result to be

{geg[1, fef[a, b, 1, mem] + fef[c, d, 1, mem]], geg[2, fef[e, f, 2, mem]]}

• MapIndexed[f[#[], #[], #2]&, Normal[assoc]]? – b3m2a1 Feb 4 at 22:46
• @b3m2a1 I couldn't get this to work really, as it gives the position of the rule inside the association (after converting it to a list of rules), rather than the position of the association in my list of associations – ThunderBiggi Feb 4 at 23:05
• Ah I misread the question. The shortest thing then is probably Table[KeyValueMap[f[##, i]&, assocs[[i]]], {i, Length@assocs}] – b3m2a1 Feb 4 at 23:07
• @b3m2a1 This does indeed work and preserves the association structure (compared to your first proposal). If you were to post it as an answer, I would upvote it, but then I will need some time to decide on which to be the accepted answer – ThunderBiggi Feb 4 at 23:19

MapIndexed[Function[{v, k},
geg[First[k], Total[KeyValueMap[fef[#1, #2, First[k], mem] &, v]]]],
{<|a -> b, c -> d|>, <|e -> f|>}]


{geg[1, fef[a, b, 1, mem] + fef[c, d, 1, mem]],
geg[2, fef[e, f, 2, mem]]}

MapIndexed[Function[{v, k},
geg[First[k],
Total[KeyValueMap[Function[{key, val}, fef[key, val, First[k], mem]], v]]]],
{<| a -> b, c -> d|>, <|e -> f|>}]


same result

With a minimal change in OP's code:

MapIndexed[geg[i = First[#2], Total[KeyValueMap[fef[#1, #2, i, mem] &, #1]]] &,
{<|a -> b, c -> d|>, <|e -> f|>}]


same result

and, without KeyValueMap:

MapIndexed[geg[i = First[#2], Total[fef[##, i, mem] & @@@ Normal[#]]] &,
{<|a -> b, c -> d|>, <|e -> f|>}]


same result

• I don't really understand how this works, can you explain it shortly (it might also be because it is past midnight here). – ThunderBiggi Feb 4 at 23:04
• @ThunderBiggi, just used Function[{x,y}, foo[x,y]] with named slots instead of foo[#1,#2]& to avoid slots #1 and #2 in the first argument of MapIndexed and in KeyValueMap. – kglr Feb 4 at 23:30
• Thank you, I didn't realise this is allowed – ThunderBiggi Feb 5 at 9:22