[Tutor] Pouring a list into a dictionary
John Miller
jmillr at umich.edu
Fri Sep 5 14:55:08 EDT 2003
With thanks to the Python Cookbook, here's code that will do something
like what you're asking for. I imagine there's a list comprehension way
to do this, but here it is with 'for' loops:
table = [('a','b','c'),(1,2,3),(4,5,6),(7,8,9)]
d1 = {}
c=0
for i in table[0]:
for j in i:
for k in table[1:]:
d1.setdefault(j, []).append(k[c])
c+=1
print d1
{'a': [1, 4, 7], 'c': [3, 6, 9], 'b': [2, 5, 8]}
John Miller
On Friday, September 5, 2003, "Allen Schmidt"
<aschmidt at fredericksburg.com> wrote:
> I have a file that I parse out to lists.
> The first line contains the column headers.
> The rest of the lines contain the rows of data elements.
>
> I need to loop through the each row, grab each column name from the
> first
> line
> and would like to use each one as the key in a dictionary.
>
> Then for each subsequent row, grab each data element and use the
> dictionary key for the correct placement as that key's value.
More information about the Tutor
mailing list