From c24d2eeb3b8613df9b9c23583a4b26a6c0934931 Mon Sep 17 00:00:00 2001 From: Jack Kamm Date: Wed, 16 Aug 2023 20:27:10 -0700 Subject: [PATCH 2/2] ob-python: Convert dicts to tables This commit to be squashed with its parent before applying --- etc/ORG-NEWS | 8 +++----- lisp/ob-python.el | 12 +++++++++--- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/etc/ORG-NEWS b/etc/ORG-NEWS index 2630554ae..509011737 100644 --- a/etc/ORG-NEWS +++ b/etc/ORG-NEWS @@ -578,11 +578,9 @@ tested property is actually present. *** =ob-python.el=: Support for more result types and plotting -=ob-python= now recognizes numpy arrays, and pandas dataframes/series, -and will convert them to org-mode tables when appropriate. - -In addition, dict results are now returned in appropriate string form, -instead of being mangled as they were previously. +=ob-python= now recognizes dictionaries, numpy arrays, and pandas +dataframes/series, and will convert them to org-mode tables when +appropriate. When the header argument =:results graphics= is set, =ob-python= will use matplotlib to save graphics. The behavior depends on whether value diff --git a/lisp/ob-python.el b/lisp/ob-python.el index 35a82afc0..3d987da2f 100644 --- a/lisp/ob-python.el +++ b/lisp/ob-python.el @@ -144,9 +144,7 @@ (defun org-babel-python-table-or-string (results) "Convert RESULTS into an appropriate elisp value. If the results look like a list or tuple, then convert them into an Emacs-lisp table, otherwise return the results as a string." - (let ((res (if (string-equal "{" (substring results 0 1)) - results ;don't covert dicts to elisp - (org-babel-script-escape results)))) + (let ((res (org-babel-script-escape results))) (if (listp res) (mapcar (lambda (el) (if (eq el 'None) org-babel-python-None-to el)) @@ -242,6 +240,14 @@ (defconst org-babel-python--def-format-value "\ else: if not set(result_params).intersection(\ ['scalar', 'verbatim', 'raw']): + def dict2table(res): + if isinstance(res, dict): + return [(k, dict2table(v)) for k, v in res.items()] + elif isinstance(res, list) or isinstance(res, tuple): + return [dict2table(x) for x in res] + else: + return res + result = dict2table(result) try: import pandas except ImportError: -- 2.41.0