Python 将字典嵌套到 reStructuredText 项目符号列表中

Python nested dictionaries into reStructuredText bullet list

我有这本字典:

d = {'B': {'ticket': ['two', 'three'], 'note': ['nothing to report']}, 'A': {'ticket': ['one'], 'note': ['my note']}, 'C': {'ticket': ['four'], 'note': ['none']}}

我正在尝试将其转换为项目符号列表形式的 .rst 文档,例如:

* A

  * ticket:

    * one

  * note

    * my note

* B

  * ticket:

    * two
    * three

  * note:

    * nothing to report

* C

  * ticket:

    * four

  * note:

    * none

我阅读了 this approach 但我无法将其翻译 成项目符号列表

感谢大家

对于像你的具体例子这样的东西,这个怎么样:

>>> for key, value in d.items():
...    print('* {}'.format(key))
...    for k, v in value.items():
...       print(' * {}:'.format(k))
...       for i in v:
...         print('  * {}'.format(i))
...
* B
 * note:
  * nothing to report
 * ticket:
  * two
  * three
* A
 * note:
  * my note
 * ticket:
  * one
* C
 * note:
  * none
 * ticket:
  * four

递归函数是解决您问题的更通用的方法:

def bullet_list(elements, level=0, indent_size=4):
    try:
        items = elements.items()
    except AttributeError:
        for bullet_point in elements:
            yield '{}* {}'.format(' ' * (indent_size * level), bullet_point)
    else:
        for bullet_point, sub_points in items:
            yield '{}* {}'.format(' ' * (indent_size * level), bullet_point)
            yield from bullet_list(sub_points, level=level + 1, indent_size=indent_size)

for line in bullet_list(d):
    print(line)

输出:

* A
    * note
        * my note
    * ticket
        * one
* C
    * note
        * none
    * ticket
        * four
* B
    * note
        * nothing to report
    * ticket
        * two
        * three

但是请注意,在 python.

的最新版本之前,字典中不能保证顺序

我会将任务分解为三个步骤:-

1 - 对字典进行排序 - 因为这是不可能的,所以最好创建一个键列表,对该列表进行排序然后遍历它们

2 - 检查票证是否存在以及票证中的项目以打印它们

3 - 检查注释是否存在,然后打印每个注释项。

又丑又脏

def bullet(d, depth=1):
    for k,v in d.items():
       print(''.join([depth * ' ', '* ', k]))
       if isinstance(v, dict):
           bullet(v, depth+1)
       else:
           for e in v:
                print(''.join([depth * ' ', ' * ', e]))