How can I pin keys with individual values ​​in my lists in python?

I import the matrix, turning the first row into keys and turning the rest of the rows into values. I want to pin keys with each value and put them in a dictionary.

ex:

If I have the following:

k = ['a', 'b'] v = [[1,2], [3,4]] 

I want to take each value in v (for x in v) and zip them (k and x) and then convert to a dictionary.

Then I will add dictionaries to the list of dictionaries.

In the end I had to:

 dicts = [{'a':1, 'b':2}, {'a':3, 'b':4}] 

Right now, I'm just pinching my lines with my keys. How to fix it?

 matrix_filename = raw_input("Enter the matrix filename: ") matrix = [i.strip().split() for i in open(matrix_filename).readlines()] keys = matrix[0] vals= (matrix[1:]) N=len(vals) dicts = [] for i in range(1,N): for j in range(1,N): vals[i-1][j-1] = int(matrix[i][j]) dicts = dict(zip(keys,vals)) 
+6
source share
2 answers
 >>> [dict(zip(k, x)) for x in v] [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}] 
+12
source

using itertools.cycle() :

 In [51]: from itertools import * In [52]: cyc=cycle(k) In [53]: [{next(cyc):y for y in x} for x in v] Out[53]: [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}] 
+3
source

All Articles