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

Question:

Suppose I have simple dictionary like this:

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

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

Asked By: LetMeSOThat4U

||

Answers:

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
Answered By: Carsten

You could also use tuples, a bit less verbose:

import chevron

tpl = """
{{#x}}
 - {{0}}: {{1}}
{{/x}}"""

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

d2 = [(k, v) for k,v in d.items()]
print(chevron.render(tpl, {"x": d2}))
Answered By: Greg Ware
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.