python - 如何在 Python 中从两个列表生成 json

标签 python json

假设我有两个列表:

table_headers = ['name', 'surname']
table_data = ['andrew', 'smith', 'bob', 'richardson']

我怎样才能做出这样的东西:

json = {
    'name': ['andrew', 'bob'], 
    'surname': ['smith','richardson']
    }

解释我在这里做什么。我正在将 html 表解析为 json,我没有找到比创建两个列表更好的方法 - 一个是标题,一个是完整数据,然后我将从两个列表中创建一个 json。

最佳答案

可能itertools中有一些函数可以让它变得更简单。

我将数据分成较小的部分,并使用zip(header,part)创建我添加到字典中的对(key, val)

table_headers = ['name', 'surname']
table_data = ['andrew', 'smith', 'bob', 'richardson']

len_headers = len(table_headers)
len_data = len(table_data)

result = dict()

for x in range(0, len_data, len_headers):
    for key, val in zip(table_headers, table_data[x:x+len_headers]):
        if key not in result:
            result[key] = []
        result[key].append(val)

print(result)

结果

{'name': ['andrew', 'bob'], 'surname': ['smith', 'richardson']}

编辑:itertools.cycle()

相同
import itertools

table_headers = ['name', 'surname']
table_data = ['andrew', 'smith', 'bob', 'richardson']

result = dict()

for key, val in zip(itertools.cycle(table_headers), table_data):
    if key not in result:
        result[key] = []
    result[key].append(val)

print(result)

编辑:并使用defaultdict()

import itertools
import collections

table_headers = ['name', 'surname']
table_data = ['andrew', 'smith', 'bob', 'richardson']

result = collections.defaultdict(list)

for key, val in zip(itertools.cycle(table_headers), table_data):
    result[key].append(val)

print(result)

import json
print(json.dumps(result))

关于python - 如何在 Python 中从两个列表生成 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55789565/

相关文章:

json - 导航 JSON 路径

java - 带有 @JsonProperty defaultValue 处理的 Jackson 模块

php - android json 发布到 php

python - 名称 'ImageDataBunch' 未定义

python - 循环遍历类实例列表

javascript - 如何使用 Jquery ajax 从 Laravel 输出 json 响应(发生错误时)

java - GSON 不返回 JSON key

python - 带参数将数据插入Spanner

python - 如何将 pandas periodIndex 转换为特定的财政年度字符串格式?

python - 将元组的 Rust 向量转换为 C 兼容结构