datatool: getting a specific value given the value of another column

I am certain this is patently obvious, but the solution is eluding me...

Given a dataset stored in CSV:

ID,    col1,  col2, col3
KEY-1, foo    bar,  baz
KEY-2, alice, bob,  chuck


I would like to define a macro \getCol3{KEY-2} that returns chuck. I am getting tripped up by what appears to be internal key structures (and the fact that I just started using datatool).

\DTLgetvalue{\thevalue}{data}{\therow}{\thecol}


is what I assumed was in the right direction, but I cannot construct valid values for \therow and \thevalue.

-

1 Answer

You need to use \DTLgetvalueforkey

\begin{filecontents*}{demo.csv}
ID,    col1,  col2, col3
KEY-1, foo,   bar,  baz
KEY-2, alice, bob,  chuck
\end{filecontents*}
\documentclass{article}
\usepackage{datatool}
\DTLloaddb{data}{demo.csv}
\newcommand*{\thevalue}{}
\newcommand*{\getCol}[2]{%
\DTLgetvalueforkey{\thevalue}{col#1}{data}{ID}{#2}%
}
\getCol{3}{KEY-2}
\show\thevalue


Here, we are using ID as the reference key to find the appropriate row, which is found using the argument #2.

-
of course, i was missing \newcommand*{\thevalue}{} ... i knew is was something simple. thanks! –  equalspeterd Jan 12 '12 at 22:42