[Tutor] Dictionaries of Tuples of Strings
Luke Paireepinart
rabidpoobear at gmail.com
Fri Feb 23 22:06:17 CET 2007
Adam Pridgen wrote:
> Hello,
>
> When I have a tuple with a single string in a dictionary entry and
> try to iterate over the tuple and it breaks the string into individual
> characters. Is this supposed to be happening?
>
> This problem is a little tricky to explain so I have included the
> output and the corresponding example code. In the example I have a
> dictionary with tuples of strings as the values. If I have more than
> one tuple, I am ok and the value is not broken into individual
> characters (look at the "type="in the code below. If I have only one
> string in the tuple value, then the string is broken into individual
> characters.
That's because you can't make tuples of single values.
Parenthesis are ways of controlling order of operation.
They don't create tuples unless there's more than one value.
Example:
>>> x = (((((((((('hello'))))))))))
>>> type(x)
<type 'str'>
>>> x = [[[[[[[[[['hello']]]]]]]]]]
>>> type(x)
<type 'list'>
Think of it like this:
a TUple needs TWO elements or more.
Solution:
use lists. They can contain single elements.
When you write
>>> x = ('somestring')
you might think it's creating a single-value tuple, but it's not.
Consider this:
y = 5
z = 23
x = (y * (z + y) / y ** 3)
In this case you wouldn't expect these parenthesis to build tuples,
would you?
Hope that helps somewhat,
-Luke
More information about the Tutor
mailing list