Reputation: 11
I am trying to add a comma (using jinja) between a list of items which are in an array of dictionaries in python.
I am doing the following:
@{@ for row in data.results -@}@
@{{@ row.gene|join(',', attribute='gene')@}}@
@{@ endfor @}@}
However, each gene belongs to a dictionary in an array of dictionaries in python, such as
'results': [
{'aminoacidic': u'p.Leu110Val',
'criterium': u'1000',
'ensembl': u'rs2301149',
'gene': u'KCNMB1',
'hgmd': u'CM078442',
'nucleotidic': u'c.328C>G'},
{'aminoacidic': None,
'criterium': u'1000',
'ensembl': u'rs13306673',
'gene': u'SLC12A3',
'hgmd': None,
'nucleotidic': u'c.283-54T>C'},
{'aminoacidic': None,
'criterium': u'3000',
'ensembl': u'rs72811418',
'gene': u'CYBA',
'hgmd': u'CR073543',
'nucleotidic': u'c.*-675A>T'}
]
I would like to have the following output:
blabla in the gene list KCNMB1, SLC12A3, and CYBA.
How can I properly add the attribute for an integer.gene in jinja so that I have the genes separated by commas? Is there any easy way to put the "and" word before the last gene?
Upvotes: 0
Views: 1216
Reputation: 2191
You can use the loop variables:
{% for result in results %}
{% if not loop.last %}{{ result.gene }}, {% else %}and {{ result.gene }}.{% endif %}
{% endfor %}
Alternatively, patch together 2 joins:
{{ (results[:results|length-1]|join(", ",attribute="gene"), (results|last).gene | join("and ") }}
In this case, we take results without the last item and join it all together with commas (results[:results|length-1]|join(", ",attribute="gene")
) then join that with the last item.
Upvotes: 2