0%

Convert Python Dictionary to Source Code of Latex and Markdown

The code is generated by [ChatGPT].

Here are two common functions, that can convert the python built-in dictionary into the format of latex/markdown unnumbered list, so that we can copy it into the latex/markdown. Example can be:

The input python dictionary is:

1
2
3
4
5
6
7
8
9
10
11
12
13
my_dict = {
"fruits": {
"apples": "red",
"bananas": "yellow",
"grapes": "purple"
},
"vegetables": {
"carrots": "orange",
"spinach": "green"
},
"meat": "beef",
"dairy": "milk"
}

The result for markdown is:

1
2
3
4
5
6
7
8
9
10
11
- fruits
- apples
- bananas
- grapes
- vegetables
- carrots
- spinach
- meat
- beef
- dairy
- milk

and result for LaTeX is:

1
2
3
4
5
6
7
8
9
10
11
12
13
\item fruits
\begin{itemize}
\item apples: red
\item bananas: yellow
\item grapes: purple
\end{itemize}
\item vegetables
\begin{itemize}
\item carrots: orange
\item spinach: green
\end{itemize}
\item meat: beef
\item dairy: milk

Function explanation: it is as simple as it shows. We use the recursion strategy here. When we are going to print a sub-dictionary, we recursively call the function, with more (two) spaces indented.

Dict to latex unnumbered list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def dict_to_latex(d, level=0):
"""
Converts a dictionary to a string in LaTeX format for an unnumbered list.
Nested dictionaries are considered as second level items.

Args:
- d (dict): The dictionary to be converted.
- level (int): The current nesting level (defaults to 0).

Returns:
- A string in LaTeX format for an unnumbered list.
"""

latex_str = ""

for k, v in d.items():
if isinstance(k, str):
k = k.replace('_', '\_')
if isinstance(v, str):
v = v.replace('_', '\_')
if isinstance(v, dict):
latex_str += f"{' '*level}\\item {k}\n\\begin{{itemize}}\n{dict_to_latex(v, level+1)}\\end{{itemize}}\n"
else:
latex_str += f"{' '*level}\\item {k}: {v}\n"

return latex_str

Note that we should avoid the _ in our string. So we need first convert it into escape character, \_.

The result of the string should be wrapped by a \begin{itemize} \end{itemize}.

Dict to markdown unnumbered list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def dict_to_markdown(d, level=0):
"""
Converts a dictionary to a string in Markdown format for an unnumbered list.
Nested dictionaries are considered as second level items.

Args:
- d (dict): The dictionary to be converted.
- level (int): The current nesting level (defaults to 0).

Returns:
- A string in Markdown format for an unnumbered list.
"""

md_str = ""

for k, v in d.items():
if isinstance(v, dict):
md_str += f"{' '*level}- {k}\n{dict_to_markdown(v, level+1)}"
else:
md_str += f"{' '*level}- {k}: {v}\n"

return md_str