Sometimes it would be nice to be able to do this, just return None in any expression evaluating for a nonexistent dict key instead of raising KeyError.
Asked
Active
Viewed 329 times
0
-
Just catch the error with a try/except statement. – wwii Apr 13 '14 at 21:28
-
@wwii: This is a *templating language*, not Python. – Martijn Pieters Apr 13 '14 at 21:42
-
Hmm, my bad, sorry about that. ```get()``` is probably the correct response even if it wasn't a template language. – wwii Apr 14 '14 at 06:27
1 Answers
1
You'd use dict.get()
to access the key instead:
<div tal:attributes="class some_dict.get(some_key)">
where the class
attribute would be omitted if some_key
is not present, as the default return value from dict.get()
is None
if the key is missing.

Martijn Pieters
- 1,048,767
- 296
- 4,058
- 3,343