Turning Mathematica lists into hashes

⇠ Back to Blog:Hacks

Here is a short hack to turn Mathematica lists into hash tables. Say that you want to apply a function~$f$ to the values associated to the following keys:

list1 = {{key1, val1}, {key2, val2}, {key7, val3}}
list2 = {{key1, val4}, {key3, val5}}
list3 = {{key2, val6}}

to have

{{key1, f[val1, val4]}, {key2, f[val2, val6]}, {key3, f[val5]}, {key7, f[val3]}}

The following function does just this:

HashList[op_, lists_] := 
 Table[{#[[1, 1]], op @@ #[[2]]}&[
 (Transpose[Select[Join @@ lists, #[[1]] == key &]])],
      {key, Union[(Join @@ lists)[[All, 1]]]}]
You use it as
HashList[f, {list1, list2, list3}]
If you had invoked
HashList[Plus, {list1, list2, list3}]
you'd get:
{{key1, val1+val4}, {key2, val2+val6}, {key3, val5}, {key7, val3}}