I am trying to find the minimum values for all elements in a list of associations, below is an example

x = {<|"a"-> 4, "b"->9, "c"->15|>, <|"a"->21, "b"->11, "c"->1|>, <|"a"->12, "b"->3, "c"->21|>}

Required output for Min {<|"a"-> 2, "b"->3, "c"->1|>}

Required output for Max {<|"a"-> 21, "b"->11, "c"->15|>}

My attempt for Max: MaximalBy[Values]@x Result: {<|"a" -> 21, "b" -> 11, "c" -> 1|>}

for Min: MinimalBy[Values]@x Result: {<|"a" -> 4, "b" -> 9, "c" -> 15|>}

Is there an elegant way to achieve this result?

New contributor
Professor Williams is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • 1
    I don't get it. How is the key a getting the value 2? That value does not appear for a in any of the associations. Similarly, why is the value of c not equal to 21 in the maximal result? – Shredderroy Dec 7 at 6:30
up vote 13 down vote accepted

How about

a = {
    <|"a" -> 4, "b" -> 9, "c" -> 15|>,
    <|"a" -> 21, "b" -> 11, "c" -> 1|>,
    <|"a" -> 12, "b" -> 3, "c" -> 21|>
};

Merge[a, Min]

(*<|"a" -> 4, "b" -> 3, "c" -> 1|>*)

Merge[a, Max]

(*<|"a" -> 21, "b" -> 11, "c" -> 21|>*)

EDIT

Improved, as per Kuba's suggestion.

Random`Private`MapThreadMin[x]
Random`Private`MapThreadMax[x]

<|"a" -> 4, "b" -> 3, "c" -> 1|>

<|"a" -> 21, "b" -> 11, "c" -> 21|>

  • 1
    is there any list out there for these "hidden" commands? Or do you happen to have a favourite list that you can share with us? – Soner Dec 7 at 12:33
  • 1
    A good try is always ?**` ;) Honestly, I learned this trick very recently from Carl Woll. Some other good place to look for such things is What are some useful undocumented Mathematica functions? – Henrik Schumacher Dec 7 at 13:45
  • Thanks, I am checking the link right now :) – Soner Dec 7 at 21:35

You may use Query and MinMax.

With x as in OP.

Query[Transpose /* Map[MinMax]]@x
<|"a" -> {4, 21}, "b" -> {3, 11}, "c" -> {1, 21}|>

You can produce a more descriptive result with AssociationThread.

res = Query[Transpose /* Map[AssociationThread[{"Min", "Max"}, MinMax@#] &]]@x
<|"a" -> <|"Min" -> 4, "Max" -> 21|>, 
  "b" -> <|"Min" -> 3, "Max" -> 11|>, 
  "c" -> <|"Min" -> 1, "Max" -> 21|>|>

Which you can then access by Key with Association's syntax sugar.

res["a", "Max"]
21

Hope this helps.

Your Answer

Professor Williams is a new contributor. Be nice, and check out our Code of Conduct.

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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