Move the outer key inward in an association
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 *)
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
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|>}