Dictionaries with tuples or tuples of tuples

Mark Lawrence breamoreboy at yahoo.co.uk
Tue Feb 19 02:37:20 CET 2013

On 19/02/2013 00:52, 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.

How about this using Python 3.

col = {"1": ((0,1,2,3),), "2": ((0,1,2,3),(2,3,4,5))}
for key,tuples in col.items():
     for t in tuples:

A slight aside, your keys look more like strings to me than numbers :)


Mark Lawrence

More information about the Python-list mailing list