【问题标题】:tomlkit: nicely formatted array with inline tablestomlkit:带有内联表的格式良好的数组
【发布时间】:2023-01-19 16:09:38
【问题描述】:

我正在尝试使用 tomlkit 0.8.0 从以下数据创建 TOML:

data = {
    'stuff': [
        {'a':1, 'b': 2},
        {'c': 3},
        {'a': 4},
    ]
}

正是这种格式:

stuff = [
    {a = 1, b = 2},
    {c = 3},
    {a = 4}, 
]

一个 simpleprint(tomlkit.dumps(data)) 创建:

[[stuff]]
a = 1
b = 2

[[stuff]]
c = 3

[[stuff]]
a = 4

如何做到这一点是一种简单的方法?

【问题讨论】:

    标签: python toml tomlkit


    【解决方案1】:

    到目前为止我发现的最好的有点复杂:

    doc = tomlkit.document()
    a = tomlkit.array()
    for x in data['stuff']:
        t = tomlkit.inline_table()
        t.update(x)
        a.add_line(t)
    a.append(tomlkit.nl())
    doc.add('stuff', a)
    print(tomlkit.dumps(doc))
    

    【讨论】:

      【解决方案2】:

      一个更简单的解决方案可以是:

      doc = tomlkit.document()
      for k, v in data.items():
          doc.add(k, v)
      print(tomlkit.dumps(doc))
      

      【讨论】:

        猜你喜欢
        • 2011-02-14
        • 1970-01-01
        • 1970-01-01
        • 2018-04-04
        • 1970-01-01
        • 2012-01-13
        • 2011-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多