Zipping two arrays of n and 2n length to form a dictionary
Quite simple really, you don't even need zip
:
{k: field_values[i::len(field_name)] for i, k in enumerate(field_name)}
# {'name': ['john', 'jane'], 'age': ['24', '26'], 'sex': ['M', 'F']}
Make use of the steps in slicing your list
, and starting with the index of the field_name
will do.
Assuming that your values are separated by a distance of 3 indices, you can do something like this without using any zip
by a single for loop. Using enumerate
gives access to index which you can leverage to access the list values. In case you want to make it more general, you can use the number of fields ('keys') as the offset.
dict_sample_fields = {}
offset = len(field_name)
for i, key in enumerate(field_name):
dict_sample_fields[key] = [field_values[i], field_values[i+offset]]
Output
{'name': ['john', 'jane'], 'age': ['24', '26'], 'sex': ['M', 'F']}
Putting it all together
dict_sample_fields = {key: [field_values[i], field_values[i+3]] for i, key in enumerate(field_name)}
We can group the values with the grouper
function from more_itertools
or with the namesake recipe in the itertools
docs. The groups can then be transposed with zip
.
>>> from more_itertools import grouper
>>>
>>> field_name = ['name', 'age', 'sex']
>>> field_values = ['john', '24', 'M', 'jane', '26', 'F']
>>>
>>> dict(zip(field_name, map(list, zip(*grouper(len(field_name), field_values)))))
{'age': ['24', '26'], 'name': ['john', 'jane'], 'sex': ['M', 'F']}
This produces no intermediate lists.