【问题标题】:How do I make a JSON file out of a list in Python?如何从 Python 中的列表中创建 JSON 文件?
【发布时间】:2014-12-19 19:25:36
【问题描述】:

我尝试制作一个看起来像这样的有效 JSON 文件:

{
    "video": [
      {"title": "New", "id": "123"},
      {"title": "New", "id": "123"}
    ]
  }

在两个包含标题和 ID 的列表中。

titles = ['New', 'New']
ids = ['123', '123']

我用 for 循环试过了

key[] = value

但它只给了我最后两项。

我也试过了

newids = {key:value for key, value in titles}

这也不起作用。

谁能给我建议怎么做?

【问题讨论】:

    标签: python json python-3.x dictionary


    【解决方案1】:

    使用zip() 配对列表:

    {'video': [{'title': title, 'id': id} for title, id in zip(titles, ids)]}
    

    video 值由列表推导形成;对于由zip() 形成的每个title, id 对,都会创建一个字典:

    >>> titles = ['New', 'New']
    >>> ids = ['123', '123']
    >>> {'video': [{'title': title, 'id': id} for title, id in zip(titles, ids)]}
    {'video': [{'title': 'New', 'id': '123'}, {'title': 'New', 'id': '123'}]}
    

    或添加一些更有趣的内容:

    >>> from pprint import pprint
    >>> titles = ['Foo de Bar', 'Bring us a Shrubbery!', 'The airspeed of a laden swallow']
    >>> ids = ['42', '81', '3.14']
    >>> pprint({'video': [{'title': title, 'id': id} for title, id in zip(titles, ids)]})
    {'video': [{'id': '42', 'title': 'Foo de Bar'},
               {'id': '81', 'title': 'Bring us a Shrubbery!'},
               {'id': '3.14', 'title': 'The airspeed of a laden swallow'}]}
    

    如果您也不知道如何使用json library 将结果编码为 JSON,以写入文件,请使用:

    import json
    
    with open('output_filename.json', 'w', encoding='utf8') as output:
        json.dump(python_object, output)
    

    【讨论】:

    • 您的答案不会创建 json 数据。它创建了一个 python 字典,应该将其转换为 json 以完成这个问题。
    • @BryanOakley:对,因为这一步是微不足道的部分,并不是问题的真正部分。
    • 非常感谢!这正是我想要的。
    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 2015-10-31
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2021-10-16
    相关资源
    最近更新 更多