# Move the outer key inward in an association

I have a list that looks like:

{15000001-><|"Loss" -> 2.85396*10^8, "Exposure" -> 6.61052*10^10|>,
15000002 -> <|"Loss" -> 1.25297*10^8, "Exposure" -> 1.57863*10^11|>,
15000003 -> <|"Loss" -> 2.05979*10^8, "Exposure" -> 6.88024*10^10|>}


I want to wind up with this:

{<|"Event"->15000001,"Loss" -> 2.85396*10^8, "Exposure" -> 6.61052*10^10|>,
<|"Event"->15000002,"Loss" -> 1.25297*10^8, "Exposure" -> 1.57863*10^11|>,
<|"Event"->15000003,"Loss" -> 2.05979*10^8, "Exposure" -> 6.88024*10^10|>}


I tried making two lists, one with Keys and one with Values and putting them together, but I couldn't quite get that to work. I'd appreciate any suggestions.

## 3 Answers

Join @@ KeyValueMap[Prepend[#2, "Event" -> #]&] /@ (Association /@ lst)


{<|"Event" -> 15000001, "Loss" -> 2.85396*10^8, "Exposure" -> 6.61052*10^10|>,
<|"Event" -> 15000002, "Loss" -> 1.25297*10^8, "Exposure" -> 1.57863*10^11|>,
<|"Event" -> 15000003, "Loss" -> 2.05979*10^8, "Exposure" -> 6.88024*10^10|>}

Alternatively, use Replace:

Replace[lst, HoldPattern[a_ -> <|b___|>] :> <|"Event" -> a, b|>, All]


same result

Here's an approach using @@@ (Apply at level {1}):

Prepend[#2, "Event" -> #] & @@@ lst
(* {
<|"Event" -> 15000001, "Loss" -> 2.85396*10^8, "Exposure" -> 6.61052*10^10|>,
<|"Event" -> 15000002, "Loss" -> 1.25297*10^8, "Exposure" -> 1.57863*10^11|>,
<|"Event" -> 15000003, "Loss" -> 2.05979*10^8, "Exposure" -> 6.88024*10^10|>
} *)


As noted by @WReach in the comments, we can also use the (undocumented?) fact that associations behave as if they had the Flat attribute (meaning that e.g. <|a->1,<|b->2|>|> evaluates to <|a->1,b->2|>):

<| "Event" -> #, #2 |> & @@@ lst
(* same output *)

• +1. Also: <| "Event" -> #, #2 |> & @@@ lst – WReach Jul 30 '19 at 4:33
• @WReach Thanks! I've added your solution as an alternative to the answer – Lukas Lang Jul 31 '19 at 8:51

Using keyPush by @alancalvitti

keyPush[newKey_][<|k_ -> as_Association|>] := Prepend[newKey -> k][as];

keyPush["Event"][Association@#] & /@ lst


{<|"Event" -> 15000001, "Loss" -> 2.85396*10^8, "Exposure" -> 6.61052*10^10|>, <|"Event" -> 15000002, "Loss" -> 1.25297*10^8, "Exposure" -> 1.57863*10^11|>, <|"Event" -> 15000003, "Loss" -> 2.05979*10^8, "Exposure" -> 6.88024*10^10|>}