From 2D table to dictionary
Alex Martelli
aleax at aleax.it
Mon Jan 21 05:46:31 EST 2002
"pekka niiranen" <krissepu at vip.fi> wrote in message
news:3C4BC9A4.20709 at vip.fi...
> How to convert 2d table to a dictionary as follows:
>
> table is 'FILE' 'co1' 'co2' 'co3'
> 'row1' 'a' 'b' 'c'
> 'row2' 'A' 'B' 'C'
>
> or in python syntax:
>
> table = [['FILE', 'co1', 'co2', 'co3'], ['row1', 'a', 'b', 'c'],
> ['row2', 'A', 'B', 'C']]
>
> How to convert it to a nested dictionary like this:
>
> d = {'row1' : {'co1': 'a', 'co2': 'b', 'co3': 'c'}, 'row2' : {'co1':
> 'A', 'co2': 'B', 'co3': 'C'}}
def table_to_nested_dict(table):
result_dict = {}
nested_keys = table[0][1:]
for a_row in table[1:]:
toplevel_key = a_row[0]
nested_values = a_row[1:]
nested_dict = result_dict[toplevel_key] = {}
for key, value in zip(nested_keys, nested_values):
nested_dict[key] = value
return result_dict
Strictly speaking, there is no _need_ for the assignments that this
function uses to name intermediate variables such as nested_keys,
toplevel_key, and so on; you COULD choose to code compactly, e.g.:
def t2nd(table):
result = {}
for a_row in table[1:]:
for key, value in zip(table[0][1:], a_row[1:]):
result.setdefault(a_row[0],{})[key] = value
return result
However, it seems to me that the first version is vastly easier
to read and understand (and maintain if/when needed).
Alex
More information about the Python-list
mailing list