4

Suppose I have simple dictionary like this:

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

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

LetMeSOThat4U
  • 6,470
  • 10
  • 53
  • 93

2 Answers2

6

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
Carsten
  • 17,991
  • 4
  • 48
  • 53
0

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}))
Greg Ware
  • 1
  • 1