python - 如何在 python 中创建 Json 模式?

标签 python json list-comprehension dictionary-comprehension

我想在 python 中创建以下 json 架构。

{
    "persons": [
        {
            "city": "Seattle", 
            "name": "Brian",
            "age" : 19
        }, 
        {
            "city": "Amsterdam", 
            "name": "David",
            "age" : 29
        }, 
        {
            "city": "Amsterdam", 
            "name": "David",
            "age" : 19
        }, 
        {
            "city": "Amsterdam", 
            "name": "David",
            "age" : 49
        }, 
        {
            "city": "Amsterdam", 
            "name": "David",
            "age" : 19
        }
    ]
}

我有 3 个列表。

    city=list_city[10::9]
    name=list_names[9::9][::-1]
    age=list_age[11::9]

我花了几个小时通过列表、字典理解来完成这一任务,但我最多只能在 person 数组中得到一个 Json 对象。

像这样:-

{
    "persons": [
        {
            "city": "Seattle", 
            "name": "Brian",
            "age" : 19
        } "age" : 19

    ]
}

我怀疑是因为字典正在更新,从而覆盖旧值。

如何实现完整的 json 架构?

最佳答案

您可以使用 zip 的列表理解来创建字典:

city=list_city[10::9]
name=list_names[9::9][::-1]
age=list_age[11::9]
final_data = {'persons':[dict(zip(['city', 'name', 'age'], i)) for i in zip(*[city, name, age])]}

关于python - 如何在 python 中创建 Json 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48708101/

相关文章:

python - 如何计算 MXNet 中损失函数的 hessian 矩阵?

python - 如何修复由于服务器阻止网页抓取而产生的这些错误?

jquery - 主干解析嵌套json

java - Spring Boot 使用 Json 作为请求参数而不是实体/模型

haskell - Haskell列表生成器中的生成器不起作用

python - 使用列表理解代替两个 for 循环

Python future 化而不用 old_div 替换/替换

Python3 导入错误 : No module named '_tkinter'

c++ - JsonCpp 如何对作为数组的 Json::Value 进行 std::sort

python - 列表理解替换二维矩阵中的循环