简体   繁体   中英

How to make a dictionary on the Latex

I want to have latex commands of this kind:

\\setdictionary{dictionary_name}{key}{value}

\\getdictionary{dictionary_name}{key}

These commands should do the same as map<string, string> in C++.

To define an associative container, there are several tools. The oldest is the keyval package, that is somehow superseded by more recent packages as pgfkeys and l3keys from LaTeX3.

l3keys and pgfkeys are initially developed as a mean to pass parameters to a macro in the form key=value . l3keys is the user interface and should be used with l3prop that implements property lists that can be associated to an object and retrieved. It is also possible to use directly l3prop, if one does not need the key=value syntax.

pgfkeys is probably simpler to use. You can define keys in a hierarchical way, set values of theses keys and retrieve it.

Basic use with pgfkeys and l3 is

\documentclass{article}
\usepackage{pgfkeys}
\usepackage{expl3,xparse}
\begin{document}
% pgfkeys version
\pgfkeyssetvalue{/my dictionary/my entry1}{Hello world!}
\pgfkeysvalueof{/my dictionary/my entry1}

% with latex3 prop
\ExplSyntaxOn
\prop_new:N \mydict    % define a container (property list)
\prop_new:N \myotherdict % and another one
\NewDocumentCommand \AddToDict { O{\mydict} m m } % add a key to a dictionary default to \mydict
{
  \prop_put:Nnn #1 {#2}{#3}
}
\NewDocumentCommand \GetFromDict { O{\mydict} m } % get a key from a dictionary default \mydict
{
  \prop_item:Nn #1 {#2}
}
\ExplSyntaxOff

\AddToDict{my entry1}{Hello again world!}
\GetFromDict{my entry1}

\AddToDict[\myotherdict]{my entry1}{Hello again again world!}
\GetFromDict[\myotherdict]{my entry1}
\end{document}

The LaTeX3 way is a bit more complex as the bundle only contains low level library routines. But it may be more flexible. Look at l3prop entry in the interface3 manual.

With pgfkeys, there many ways to enter values, retrieve them, set default values, associate code to a key, etc. Look at 'key management' in the tikz manual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM