Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zipping two arrays of n and 2n length to form a dictionary

Tags:

python

I am struggling with this little thingy. Suppose:

field_name = ['name', 'age', 'sex']
field_values = ['john', '24', 'M', 'jane', '26', 'F']

output something like:

{  'name': ['john','jane'],
   'age': ['24', '26'],
   'sex': ['M', 'F']
}

Zipping right now:

dict_sample_fields = dict(zip(field_name, field_value))
#output
{  'name': 'john',
   'age': '24',
   'sex': 'M'
}

How do I achieve a cyclic zipping on values?

I can achieve this long way having multi-loops. One-liner would be cool :D.

like image 493
NoorJafri Avatar asked Jan 08 '19 13:01

NoorJafri


1 Answers

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.

like image 74
r.ook Avatar answered Oct 13 '22 00:10

r.ook