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>
The comma makes the tuple. Without it you just have a single value 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 eachlinkis a string, which you try to index by another string, resulting in the exception.