Given a list of associations tab
where each association has keys {"name", "a", "b"}
:
SeedRandom[2018]
n = 100;
names = RandomWord[n];
tab := Table[<|"name" -> names[[i]], "a" -> RandomReal[10],
"b" -> RandomReal[10]|>, {i, n}]
tab0 = tab
(* {<|"name" -> "nuke", "a" -> 4.41839, "b" -> 0.688305|>,
<|"name" -> "iodine", "a" -> 6.61215, "b" -> 4.315|>,
... } *)
and a static list of the form {"nameValue", "a"}
or {"nameValue", "b"}
:
randomNames = RandomSample[names, n];
list = Table[{randomNames[[i]], RandomChoice[{"a", "b"}]}, {i, n}]
(* {{"waterspout", "a"}, {"encouraging", "a"}, {"saber", "b"}, ... } *)
what is the fastest way of extracting the values from tab
based on list
? For example if list
contains {"nuke","a"}
it should return 4.41839
but if it contains {"nuke","b"}
it should return 0.688305
.
Important additional information
- Each name value in
tab
is exactly once inlist
(in particular,list
andtab
have the same length) - The structure of
tab
andnames
is always the same, only the values for the keysa
andb
change (i.e. everything except the numerical values is static). The solution can have a high fixed cost, but after that should run as fast as possible on every new evaluation oftab
.
The following works but is quite slow (about 0.01 second):
Table[First[Select[tab0, #["name"] == list[[i, 1]] &, 1]][list[[i, 2]]], {i, n}]
(* {2.48345, 8.47655, 7.92796, 1.6882, ..., 3.65979} *)
tab
comes from a stream and is updated at high frequency. But you can work ontab0
if you want :). I want to processtab
as fast as possible and wanted to highlight what changes (= the numerical values) and what is static. $\endgroup$tab
changed all the time... =D $\endgroup$tab
andlist
never change? $\endgroup$