Search code examples
pythonmustachepystache

Iterating over keys and values of a dictionary in mustache / pystache


Suppose I have simple dictionary like this:

d = {'k1':'v1', 'key2':'val2'}

How can I render key, value lines in pystache using that dictionary?


Solution

  • You have to transform your dictionary a bit. Using the mustache syntax, you can only iterate through lists of dictionaries, so your dictionary d has to become a list where each key-value pair in d is a dictionary with the key and value as two separate items, something like this:

    >>> [{"k": k, "v": v} for k,v in d.items()]
    [{'k': 'key2', 'v': 'val2'}, {'k': 'k1', 'v': 'v1'}]
    

    Complete sample program:

    import pystache
    
    tpl = """\
    {{#x}}
     - {{k}}: {{v}}
    {{/x}}"""
    
    d = {'k1':'v1', 'key2':'val2'}
    
    d2 = [{"k": k, "v": v} for k,v in d.items()]
    pystache.render(tpl, {"x": d2})
    

    Output:

     - key2: val2
     - k1: v1