3 回答
TA贡献1802条经验 获得超10个赞
可能有一些功能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))
TA贡献1934条经验 获得超2个赞
假设保证表数据具有正确数量的数据条目以创建偶数行(根据您的标题计数)
您可以使用良好的旧 json 包,并创建您想要的
import json
# a very nice python package
d = {header: table_data[i::len(table_headers)] for i,header in
enumerate(table_headers)}
return json.dumps(d)
TA贡献1818条经验 获得超8个赞
您可以按以下方式本机执行此操作(无需任何导入或特殊功能):
table_headers = ['name', 'surname']
table_data = ['andrew', 'smith', 'bob', 'richardson']
num_of_cols = len(table_headers)
cols = [[x for x in table_data[i::num_of_cols]] for i in range(num_of_cols)]
print(dict(zip(table_headers, cols)))
## {'name': ['bob', 'andrew'], 'surname': ['smith', 'richardson']}
添加更多数据:
table_data.extend(['john', 'doe'])
cols = [[x for x in table_data[i::num_of_cols]] for i in range(num_of_cols)]
print(dict(zip(table_headers, cols)))
## {'name': ['andrew', 'bob', 'john'], 'surname': ['smith', 'richardson', 'doe']}
添加更多标题列:
table_headers = ['name', 'surname', 'middle_initial']
table_data = ['andrew', 'smith', 'a.','bob', 'richardson', 'b.']
num_of_cols = len(table_headers)
cols = [[x for x in table_data[i::num_of_cols]] for i in range(num_of_cols)]
print(dict(zip(table_headers, cols)))
## {'name': ['andrew', 'bob'], 'surname': ['smith', 'richardson'], 'middle_initial': ['a.', 'b.']}
添加回答
举报