假设我有两个列表:
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/