Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 439
mrkafk Avatar asked Oct 26 '25 14:10

mrkafk


1 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
like image 195
Carsten Avatar answered Oct 29 '25 04:10

Carsten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!