Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and populating a dictionary in jinja2

import jinja2 
from jinja2 import Template

records = [{'a':1,'b':1, 'c':1},{'a':1,'b':1, 'c':1}, {'a':2,'b':1, 'c':1}, {'a':3,'b':1, 'c':1}]    

t = jinja2.Template("""
{% set record_info = dict() %}
{% for item in records %}
{% set key =  str(item['a'])+str(item['b'])+str(item['c']) %}
{% if key in record_info %}
{% set record_info.key += 1 %}
{% else %}
{% set record_info.key = 1 %}
{% endif %}
{% endfor %}
{{record_info}}""")    

This gives me:

Traceback (most recent call last):
  File "<stdin>", line 11, in <module>
  File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 945, in __new__
    return env.from_string(source, template_class=cls)
  File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 880, in from_string
    return cls.from_code(self, self.compile(source), globals, None)
  File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 591, in compile
    self.handle_exception(exc_info, source_hint=source_hint)
  File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "<unknown>", line 6, in template
jinja2.exceptions.TemplateSyntaxError: expected token 'end of statement block', got '.'

What am I doing wrong ?

like image 573
Ankur Agarwal Avatar asked Jul 08 '17 02:07

Ankur Agarwal


1 Answers

I was able to do it like this, any improvements?

records = [{'a':1,'b':1, 'c':1},{'a':1,'b':1, 'c':1}, {'a':2,'b':1, 'c':1}, {'a':3,'b':1, 'c':1}]    
t = jinja2.Template("""
{% set record_info = dict() %}
{% for item in records %}
{% set key =  item['a'] ~ ':' ~ item['b'] ~ ':' ~ item['c'] %}
{% if key in record_info %}
{% set _dummy = record_info.update( {key: record_info[key]+1 })  %}
{% else %}
{% set _dummy = record_info.update({ key:1 }) %}
{% endif %}
{% endfor %}
{{record_info}}""")    
print t.render(records=records)

{u'1:1:1': 2, u'3:1:1': 1, u'2:1:1': 1}
like image 95
Ankur Agarwal Avatar answered Sep 23 '22 21:09

Ankur Agarwal