Building a dict from a tuple of tuples
MRAB
python at mrabarnett.plus.com
Sat Feb 20 20:54:20 CET 2010
vsoler wrote:
> On Feb 20, 7:00 pm, MRAB <pyt... at mrabarnett.plus.com> wrote:
>> vsoler wrote:
>>> Hello everyone!
>>> I have a tuple of tuples, coming from an Excel range, such as this:
>>> ((None, u'x', u'y'),
>>> (u'a', 1.0, 7.0),
>>> (u'b', None, 8.0))
>>> I need to build a dictionary that has, as key, the row and column
>>> header.
>>> For example:
>>> d={ (u'a',u'x'):1.0, (u'a',u'y'): 7.0, (u'b',u'y'):8.0 }
>>> As you can see, if the value in the matrix is None, no key has to be
>>> added to the dictionary.
>>> Of course, my tuple of tuples is a lot bigger.
>>> How can I possibly do this?
>>> Thank you
>> Does this help?
>>
>> matrix = ((None, u'x', u'y'),
>> (u'a', 1.0, 7.0),
>> (u'b', None, 8.0))
>>
>> for row in matrix[1 : ]:
>> for col, val in zip(matrix[0][1 : ], row[1 : ]):
>> print row[0], col, val
>
> and the dictionary?
>
> it is the ultimate goal of what I am intending...
>
> Thank you
The difficult bit is working out how to produce the keys and values for
the dict from the tuple of tuples, and I've shown you that. The rest is
straightforward.
More information about the Python-list
mailing list