Help: From 2D table to dictionary

Michal Wallace sabren at manifestation.com
Mon Jan 21 03:32:06 EST 2002


On Mon, 21 Jan 2002, pekka niiranen wrote:

> I have got this far but forming the dictionary proved more difficult
> than I expected:
>
> table
> [['FILE', 'co1', 'co2', 'co3'], ['row1', 'a', 'b', 'c'], ['row2', 'A',
> 'B', 'C']]
> for row in table[1:]:
> ...     for col in table[0][1:]:
> ...         x = table.index(row)
> ...         y = table[0].index(col)
> ...         print x, y, table[x][y]


Here's one answer.

When you go to work with the table, make sure you use
colnames and rownames to put them back in the right order,
since the dictionary won't preserve it.

##-- cut --##
"""
Program to turn a 2D table into a 2D dictionary.
"""

table = [['FILE', 'co1', 'co2', 'co3'],
         ['row1', 'a', 'b', 'c'],
         ['row2', 'A', 'B', 'C']]

colnames = table[0][1:]
rownames = [row[0] for row in table[1:]]

dictable = {}
for r in range(len(rownames)):
    rowname = rownames[r]
    thisrow = {}
    for c in range(len(colnames)):
        thisrow[colnames[c]]=table[r+1][c+1]
    dictable[rowname] = thisrow

assert dictable == {'row1' : {'co1': 'a', 'co2': 'b', 'co3': 'c'},
                    'row2' : {'co1': 'A', 'co2': 'B', 'co3': 'C'}}

##-- cut --##

:) That was fun!


Cheers,

- Michal   http://www.sabren.net/   sabren at manifestation.com
------------------------------------------------------------
Give your ideas the perfect home: http://www.cornerhost.com/
 cvs - weblogs - php - linux shell - perl/python/cgi - java
------------------------------------------------------------





More information about the Python-list mailing list