【问题标题】:Create a JSON dict from a list of values from a tuple and a separate list of keys从元组中的值列表和单独的键列表创建 JSON dict
【发布时间】:2016-10-11 02:57:52
【问题描述】:

我有一个元组列表,想从中生成 JSON

[(1, 'a', 'A'), (2, 'b', 'B'), (3, 'c', 'C'), (4, 'd', 'D'), (5, 'e', 'E'), (6, 'f', 'F'), (7, 'g', 'G'), (8, 'h', 'H'), (9, 'i', 'I')]

预期的 JSON

{
    "List": [
                {
                    "name": "1",
                    "description": "a",
                    "type": "A"
                },
                {
                    "name": "2",
                    "description": "b",
                    "type": "B"
                },
                {
                    "name": "3",
                    "description": "c",
                    "type": "C"
                },
               and so on....
            ]
}

我该怎么做?

重复的已识别答案无效并出现此错误

ValueError: dictionary update sequence element #0 has length 3; 2 is required

【问题讨论】:

  • 这不起作用,给出错误 ValueError: dictionary update sequence element #0 has length 3; 2 是必需的
  • 他可能只阅读了您的标题,这听起来确实像是您想要完全按照提名副本中的内容进行操作。我会为你编辑你的标题。
  • @tripleee:行动带来责任,如果他足够积极地将其标记为重复,那么他还必须对其进行必要的研究,因为当人们在 SO 中看到 DUPLICATE 时,他们开始投反对票
  • 我担心在发布问题时创建有用的标题的负担是在你身上。请理解,消除噪音以保持该站点上的信号可接受是一项重大工作,主要由无偿志愿者处理。但个别错误通常是无害的,特别是如果你能迅速纠正任何误解。

标签: python json


【解决方案1】:

zip 键和每个 tuple 在结果上调用 dict 然后 json.dumps:

import json
keys = ["name", "description","type"]

l=[(1, 'a', 'A'), (2, 'b', 'B'), (3, 'c', 'C'), (4, 'd', 'D'), (5, 'e', 'E'), (6, 'f', 'F'), (7, 'g', 'G'), (8, 'h', 'H'), (9, 'i', 'I')]


js =  json.dumps({"List":[dict(zip(keys, tup)) for tup in l]})

这给了你:

'{"List": [{"type": "A", "name": 1, "description": "a"}, {"type": "B", "name": 2, "description": "b"}, {"type": "C", "name": 3, "description": "c"}, {"type": "D", "name": 4, "description": "d"}, {"type": "E", "name": 5, "description": "e"}, {"type": "F", "name": 6, "description": "f"}, {"type": "G", "name": 7, "description": "g"}, {"type": "H", "name": 8, "description": "h"}, {"type": "I", "name": 9, "description": "i"}]}'

【讨论】:

  • 非常感谢,但我认为 OrderedDict 对我来说会更好。无论如何再次感谢
猜你喜欢
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-09
  • 1970-01-01
相关资源
最近更新 更多