11

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.

Mitchell Kaplan
  • 3,696
  • 22
  • 34

3 Answers3

14

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 *)
Lukas Lang
  • 33,963
  • 1
  • 51
  • 97
11
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

kglr
  • 394,356
  • 18
  • 477
  • 896
3

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

Rohit Namjoshi
  • 10,212
  • 6
  • 16
  • 67