Probably there is some function in itertools which could make it simpler.
I split data in smaller parts and use zip(header, part) to create pairs (key, val) which I addd to dictionary
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)
Result
{'name': ['andrew', 'bob'], 'surname': ['smith', 'richardson']}
EDIT: the same with 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)
EDIT: and with 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))
dictcontainingsets. Do you want a Python object, or a JSON-formatted string? Also, your question title says twodicts, but the body says twolists.