11
$\begingroup$

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.

$\endgroup$
11
$\begingroup$
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

$\endgroup$
14
$\begingroup$

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 *)
$\endgroup$
  • 3
    $\begingroup$ +1. Also: <| "Event" -> #, #2 |> & @@@ lst $\endgroup$ – WReach Jul 30 at 4:33
  • $\begingroup$ @WReach Thanks! I've added your solution as an alternative to the answer $\endgroup$ – Lukas Lang Jul 31 at 8:51
3
$\begingroup$

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.