Reputation: 59
there I have been trying to show list of dictionaries in Jinja template. I need to show key only once as both dictionary have same key. However, value needs to be shown in different column in same rows as key. Problem is its keep showing key and value in same column.
Bellow is my code.
{%for r in result%}
{%for keyCategory, valueCategory in r.items()%}
<div class="jumbotron p-3" style="margin-bottom: 5px;">
<div class="row">
<div class="col-lg-4">
<label class=" text-right">{{keyCategory}}</label>
</div>
<div class="col-lg-2">
<input type="text" class="form-control text-left" id="idInput{{ keyCategory }}"
value="{{ valueCategory }}">
</div>
</div>
</div>
{%endfor%}
{%endfor%}
Upvotes: 0
Views: 241
Reputation: 558
I would like you to suggest that first, you modify the list
and then iterate.
Modify using itertools.groupby: https://www.google.com/amp/s/www.geeksforgeeks.org/itertools-groupby-in-python/amp/
Your code should look like
final_result = defaultdict(list)
for d in result:
for k, v in d.items():
final_result[k].append(v)
{%for r in final_result%}
<div class="jumbotron p-3" style="margin-bottom: 5px;">
<div class="row">
<div class="col-lg-4">
<label class=" text-right">{{r['key']}}</label>
</div>
{%for value in r.values%}
<div class="col-lg-2">
<input type="text" class="form-control text-left" id="idInput{{ value }}"
value="{{ value }}">
</div>
{%endfor%}
</div>
</div>
{%endfor%}
Try this.
Correct if it doesn't work.
Edit 1: I think what you want to do, can be implemented using below code
{%for r in result[0].keys()%}
{%for row in result%}
<div class="jumbotron p-3" style="margin-bottom: 5px;">
<div class="row">
<div class="col-lg-4">
<label class=" text-right">{{ r }}</label>
</div>
<div class="col-lg-2">
<input type="text" class="form-control text-left" id="idInput{{ keyCategory }}"
value="{{ row[r] }}">
</div>
</div>
</div>
{%endfor%}
{%endfor%}
Upvotes: 1
Reputation: 59
It is working fine after replacing r.values
to final_result[r]
in for-loop
{%for r in final_result.keys()%}
<div class="jumbotron p-3" style="margin-bottom: 5px;">
<div class="row">
<div class="col-lg-4">
<label class=" text-right">{{r}}</label>
</div>
{%for value in final_result[r]%}
<div class="col-lg-2">
<input type="text" class="form-control text-left" id="idInput{{ value }}" value="{{ value }}">
</div>
{%endfor%}
</div>
</div>
{%endfor%}
Upvotes: 0