Reputation: 187
I am importing a matrix, turning the first row into keys, and turning the rest of the rows into values. I want to zip the 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) then convert to a dictionary.
Then I will add the dictionaries to a list of dictionaries.
At the end I should have:
dicts = [{'a':1, 'b':2}, {'a':3, 'b':4}]
Right now, I am only zipping my rows with my keys. How do I fix this?
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))
Upvotes: 6
Views: 2391
Reputation: 21
I developed a generator-based solution, based on answers from another question.
(duplicate of answer: https://stackoverflow.com/a/69578838/11121534)
This might be helpful when the dict is huge.
def zip_dict(d):
for vals in zip(*(d.values())):
yield dict(zip(d.keys(), vals))
Example usage:
d = dict(
x=[1,3,5,7,9],
y=[2,4,6,8,10]
)
for t in zip_dict(d):
print(t)
The result would be:
{'x': 1, 'y': 2}
{'x': 3, 'y': 4}
{'x': 5, 'y': 6}
{'x': 7, 'y': 8}
{'x': 9, 'y': 10}
Upvotes: 0
Reputation: 4976
>>> [dict(zip(k, x)) for x in v]
[{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]
Upvotes: 13
Reputation: 250941
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}]
Upvotes: 3