Dictionaries with tuples or tuples of tuples

Mitya Sirenef msirenef at lightbird.net
Mon Feb 18 20:11:05 EST 2013


On 02/18/2013 07:52 PM, Jon Reyes wrote:
> So I have a dictionary and the  key is a number. The values are either a single tuple or a tuple of 
tuples. Is there a better way to go about accessing the values of the 
dictionary? All the tuples contain four elements.
 >
 > So say:
 > col = {"1": (0,1,2,3): "2": ((0,1,2,3),(2,3,4,5))}
 >
 > Then to access the values of the tuple I'd do this:
 >
 > for key,value in col.iteritems():
 > if isinstance(value[0], tuple):
 > #iterate through the tuples of a tuple
 > else:
 > #iterate through the tuple
 >
 > At first I was thinking that I could just put the same keys with just 
single tuples on a dictionary but only one tuple exists when I iterate 
through the dictionary. I'm sorry, I'm really new at Python and I just 
grab anything I can when I need it from Google and the Python docs.

It would be easier to process if, when adding a single tuple
to the dict, you could wrap it inside a tuple: (mytup,)

If your data set is not very large and you don't mind the
slight performance hit, you can simplify processing step:

for k,v in col.iteritems():
     if not isinstance(v[0], tuple):
         v = (v,)
     for tup in v: ...


-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Although the most acute judges of the witches and even the witches
themselves, were convinced of the guilt of witchery, the guilt nevertheless
was non-existent. It is thus with all guilt.  Friedrich Nietzsche




More information about the Python-list mailing list