Reputation: 54764
SymPy will pretty print expressions within a dict
like this:
>>> latex(dict(a=1, b=2))
'\\left \\{ a : 1, \\quad b : 2\\right \\}'
Instead I'd like to use the align
environment to split my expressions across lines, with an output like this:
\begin{align}
a & = 1 \\
b & = 2 \\
\end{align}
Can SymPy do this for me?
Upvotes: 4
Views: 585
Reputation:
There is no built-in option for this, but you can subclass LatexPrinter and override its method _print_dict
to do whatever you want, like this:
from sympy.printing.latex import LatexPrinter
class MyPrinter(LatexPrinter):
def _print_dict(self, d):
keys = sorted(d.keys(), key=default_sort_key)
items = []
for key in keys:
val = d[key]
items.append("%s & = %s" % (self._print(key), self._print(val)))
return r"\begin{align} %s \end{align}" % r", \\ ".join(items)
Example of use:
mydict = {'a': 1, 'b': 2}
print(MyPrinter().doprint(mydict)) # \begin{align} a & = 1, \\ b & = 2 \end{align}
The latex
function is just a shortcut for LatexPrinter(settings).doprint(expr)
, you can redefine it accordingly:
latex = lambda expr, **settings: MyPrinter(settings).doprint(expr)
so that latex
has the new behavior.
Speaking of settings, one can also introduce a setting for this, so that both printing methods are available; but at that stage it's probably better to add an issue and PR to SymPy repo.
Upvotes: 1