# Applying Switch and Which to mixed-Key Association lists

Given an Association list w/ a common Key but also some distinct ones:

data3 = {<|"commonKey" -> 1, "b" -> 3|>, <|"commonKey" -> 2,
"c" -> 4|>} // Dataset


How to implement logic similar to Switch and Which using named slots?

data3[All, Switch[#commonKey, 1, #b] &] // Normal


{3, Missing["Failed"]}

data3[All, Switch[#commonKey, 1, #b, 2, #c] &] //Normal


{Missing["Failed"], Missing["Failed"]}

Similarly, using Which:

data3[All, Which[#commonKey == 1, #b, #commonKey == 2, #c] &]//Normal


{Missing["Failed"], Missing["Failed"]}

The cause is Function::slota Named Slot can't be filled from the association with the Key that is missing.

Is there an elegant workaround that can be mapped on existing Association list, as opposed to aggregating via GroupBy[#commonKey&]? (Reason: the actual data set that is simplified here is chronologically sorted, and grouping would not preserve the item sequence).

• You really are trying to save time by abbreviating with w/ w/?? – halirutan May 12 '15 at 0:27
• Programmable: w/, w/i, w/o ... – alancalvitti May 12 '15 at 18:03

data3[All, Switch[#commonKey, 1, #["b"], _, 0] &]

• Not sure where the 0 comes from but did you mean to write this? data3[All, Switch[#commonKey, 1, #["b"], 2, #["c"]] &]? That works while Switch[#commonKey, 1, #b, 2, #c] . – alancalvitti May 12 '15 at 18:09
• @alancalvitti I meant to write it because I thought you might want a fallback rule if there isn't any #b in the association. You can just remove the part and adapt if like you want. – halirutan May 12 '15 at 19:18