richzilla
richzilla

Reputation: 42062

python - single item tuple throws exception in for statement

Im curious as to why this happens. Im using Mako templates to iterate over a tuple, that contains a number of number of dictionaries, that in turn contain link information:

links = (
        {
            'path' : request.route_url('home'),
            'text' : 'Home'
        },
        {
            'path' : "http://www.microsoft.com",
            'text' : "Microsoft"
        }
    )

if i send the above to the view, everything works as expected, the links are displayed. If i remove the second link however:

links = (
            {
                'path' : request.route_url('home'),
                'text' : 'Home'
            }
)

i get an exception: TypeError: string indices must be integers, not str

if i put a comma after the end of the dictionary, things start working again. Can anyone explain what is going on?

Edit Mako template snippet

<nav>

       % for link in links:
        <a href="${link['path']}">${link['text']}</a>
       % endfor

      </nav>

Upvotes: 0

Views: 437

Answers (1)

Jochen Ritzel
Jochen Ritzel

Reputation: 107686

if i put a comma after the end of the dictionary, things start working again. Can anyone explain what is going on?

The comma makes the tuple. Without it you just have a single value in brackets.

x = ({}) # brackets around a dict
x = {}, # a 1-tuple
x = ({},) # a 1-tuple in brackets

Often it appears that the brackets are the notation for tuples, because they appear together so often. That's only because for syntactic reasons, you often need the brackets when writing a tuple.

When you write links = ({ ... }) you have only a dictionary, not a tuple. Python loops over it's keys, so each link is a string, which you try to index by another string, resulting in the exception.

Upvotes: 5

Related Questions