Search code examples
pythonmako

How to check if a key exists in mako dict?


Say if I have the following:

mydict = {
   a: 'A'
}

How do I check if key a exists in the dictionary? Pseudocode below:

%if 'a' in mydict.keys()
  ${mydict['a']}
%endif

Solution

  • You can just use in:

    from mako.template import Template
    t = Template("""
    % if key in d:
        key is in dictionary
    % else:
        key is not in dictionary
    % endif
    """)
    
    
    print t.render(key='a', d={'a': 'A'})  # prints "key is in dictionary"