Access dictionary within dictionary jinja - python

I have a list of dictionaries called data.
for every_archive in data I want to acces every_archive['key1']['key2']
First key it's a constant: "units" but the second key depends on a loop.
I have already tried : {{ archive['units'][{{item['param']}}] }}
where item['param'] item is another iterator in a loop and item['param'] is the second key.

See the format below! The structure is going to be very similar to how you would loop through a dictionary in Python, but with the jinja {% %} for each statement you do not want to display and {{ }} around each expression you want to display.
Taken from How to iterate through a list of dictionaries in jinja template?
Data: parent_dict = [{'A':{'a':1}},{'B':{'b':2}},{'C':{'c':3}},{'D':{'d':4}}]
In Jinja2 iteration:
{% for dict_item in parent_dict %}
{% for key1 in dict_item %}
{% for key2 in dict_item[key1] %}
<h2>Value: {{dict_item[key1][key2]}}</h2>
{% endfor %}
{% endfor %}
{% endfor %}

As far as I understood, you have a list that contains some nested dictionaries; if that's the case, and your data looks like that:
data = [{'foo': {'bar1': 'buzz1', 'bar2': 'buzz2'}}, {'foo': {'bar3': 'buzz3', 'bar4': 'buzz4'}}]
if you use this Jinja2:
{% for every_archive in data %}
{% for key1, archive1 in every_archive.items() %}
{% for key2, value2 in archive1.items() %}
<p>{{ key1 }} - {{ key2 }} - {{ value2 }}</p>
{% endfor %}
{% endfor %}
{% endfor %}
you will get this output:
foo - bar1 - buzz1
foo - bar2 - buzz2
foo - bar3 - buzz3
foo - bar4 - buzz4
also, the same output you will get from
<p>{{ key1 }} - {{ key2 }} - {{ archive1[key2] }}</p>

Related

Iterating through Python dictionary with Jinja2

I've scoured the internet and can't seem to find the solution that fits my case.
I have a dictionary:
{"1528430400000": 129, "1528516800000": 123.14, "1528603200000": 117.28, "1528689600000": 111.42, "1528776000000": 105.56, "1528862400000": 99.7, "1528948800000": 93.84, "1529035200000": 87.98, "1529121600000": 82.12, "1529208000000": 76.26, "1529294400000": 70.4, "1529380800000": 64.54, "1529467200000": 58.68, "1529553600000": 52.82, "1529640000000": 46.96, "1529726400000": 41.1, "1529812800000": 35.24, "1529899200000": 29.38, "1529985600000": 23.52, "1530072000000": 17.66, "1530158400000": 11.8, "1530244800000": 5.94, "1530331200000": 0.08, "1530417600000": 0}'
where each key is a javascript-formatted date.
I'm looking for a simple iteration through each key and value.
example:
{% for key,value in dict %}
{{key}}, {{value}}
{% endfor %}
Use:
{% for key, value in dict.items() %}
<h1>Key: {{key}}</h1>
<h2>Value: {{value}}</h2>
{% endfor %}
let's suppose your dictionary is "my_dict".
view.py (django) will have-
return render(request, 'template', { 'my_dict' :
my_dict })
HTML page will have-
{% for k,v in my_dict.items %}
{{ k }}: {{ v }} <br>
{% endfor %}
You can pass dict.items to the template rendering object:
return flask.render_template('template_name', data = the_dict.items())
Then, in the HTML:
{%for a, b in data%}
<span>Key: {{a}}, value: {{b}}</span>
{%endfor%}
{% if dict_var |type_debug == 'dict' %}
{% for key in dict_var %}
{{ key }}: "{{ dict_var[key] }}"
{% endfor %}
{% endif %}
use this will error: ValueError: too many values to unpack in sometimes
{% if dict_var |type_debug == 'dict' %}
{% for key, value in dict_var %}
{{ key }}: "{{ value }}"
{% endfor %}
{% endif %}

Render list in ordered structure without unicode characters

I have a list that looks like this:
[(u'Element1', u'Description1', u'Status1), (u'newElement2', u'newDescription2', u'newStatus2), (u'nextElement3', u'nextDescription3', u'nextStatus3), (u'anotherElement4', u'anotherDescription4', u'anotherStatus4)]
I have an ansible playbook that uses a jinja2 template to render the list to a text file. The template file looks like this:
{% for item in description | batch(3, ' ') %}
{% for el in item %}
{{ el }}
{% endfor %}
{% endfor %}
But this returns the text file to look like this:
[u'Element1', u'Description1', u'Status1]
[u'newElement2', u'newDescription2', u'newStatus2]
[u'nextElement3', u'nextDescription3', u'nextStatus3]
[u'anotherElement4', u'anotherDescription4', u'anotherStatus4]
What I want the report to look like is this:
Element1 Description1 Status1
newElement2 nextDescription2 newStatus2
nextElement3 nextDescription3 nextStatus3
anotherElement4 anotherDescription4 anotherDescription4
Is there a way to remove the unicode characters and render the lists this way?
For example:
{% for row in description %}
{% for cell in row %}
{{ "%-22s"|format(cell) }}
{%- endfor %}
{% endfor %}
Yields:
Element1 Description1 Status1
newElement2 newDescription2 newStatus2
nextElement3 nextDescription3 nextStatus3
anotherElement4 anotherDescription4 anotherStatus4
But to get a dynamic padding - depending on a max length of an element in a column - looks like a much more complex task: {{ "%-22s"|format(cell) }} can be replaced with {{ "{0}".format(cell).ljust(width) }} where width can be a variable, but likely it would require another loop first to collect the lengths.
You could try
{% for el in item %}
{% for e in el %}
{{ e }}
{% endfor %}
{% endfor %}
Or use html tables if you want to be able to change formatting

How to tell list from non-list in Django template?

I've got a Django template I'd sometimes like to pass a list and sometimes like to pass a single value. How can the template tell which it was given?
I'm thinking the value would be set like one of these:
context = {
'foo' : 'bar
}
or:
context = {
'foo' : ['bar', 'bat', 'baz']
}
Then, the template would have code that looks something like this:
{% if foo isa list %}
{% for item in foo %}
{{ item }}<br>
{% endfor %}
{% else %}
{{ item}}<br>
{% endif %}
I can set it up to have foo or foolist, for example, and check for one or the other. However, it'd be a bit nicer (imo) to just have foo that was either a list or not.
If you intend to do it this way then just add a check that it doesn't have format(in case of string) method and has 0 index, if so then its a list else considered single value
{% if foo.0 and not foo.format %}
{% for item in foo %}
{{ item }}<br>
{% endfor %}
{% else %}
{{ item}}<br>
{% endif %}
I think your approach is needlessly complicated.
I would just go with a list:
views.py
foo_list = ['bar']
context = {
'foo': foo_list,
'foo_len': len(foo_list),
}
template
{% if foo_len == 1 %}
{{ foo.0 }}
{% else %}
{% for item in foo %}
{{ item }}
{% endfor %}
{% endif %}

Django template and part of a dictionary of lists

in Django I want to display some entries in a dictionary of lists.
My context is:
keys = ['coins', 'colors']
dict = {'colors':['red', 'blue'],
'animals':['dog','cat','bird'],
'coins':['penny','nickel','dime','quarter'] }
Template code:
<ul>{% for k in keys %}
<li>{{ k }}, {{ dict.k|length }}: [{% for v in dict.k %} {{ v }}, {% endfor %}]
{% endfor %}</ul>
I want to see:
* coins,4: [penny, nickel, dime, quarter,]
* colors,2: [red, blue,]
But what I actually see is keys but no values:
* coins,0: []
* colors,0: []
Note: I also tried dict.{{k}} instead of dict.k, but as expected that just gave a parse error in template rendering. I'll get rid of the trailing comma with forloop.last after getting the basic list working.
What is the secret sauce for displaying selected values from a dictionary of lists?
The question django template and dictionary of lists displays an entire dictionary, but my requirement is to display only a few entries from a potentially very large dictionary.
The problem (as you suspected) is that dict.k is evaluated to dict['k'] where 'k' is not a valid key in the dictionary. Try instead to iterate each item pair using dict.items and only display the results for the keys you're concerned with:
<ul>{% for k, v in dict.items %}
{% if k in keys %}
<li>
{{ k }}, {{ v|length }}: [{% for val in v %} {{ val }},{% endfor %}]
</li>
{% endif %}
{% endfor %}
</ul>
<ul>
{% for k, v in dict.items %} # instead of iterating keys, iterate dict
{% if k in keys %} # if key found in keys
<li>
{{ k }}, {{ v|length }}: [{% for val in v %} {{ val }},{% endfor %}]
</li>
{% endif %}
{% endfor %}
</ul>

how to iterate through dictionary in a dictionary in django template?

My dictionary looks like this(Dictionary within a dictionary):
{'0': {
'chosen_unit': <Unit: Kg>,
'cost': Decimal('10.0000'),
'unit__name_abbrev': u'G',
'supplier__supplier': u"Steve's Meat Locker",
'price': Decimal('5.00'),
'supplier__address': u'No\r\naddress here',
'chosen_unit_amount': u'2',
'city__name': u'Joburg, Central',
'supplier__phone_number': u'02299944444',
'supplier__website': None,
'supplier__price_list': u'',
'supplier__email': u'ss.sss#ssssss.com',
'unit__name': u'Gram',
'name': u'Rump Bone',
}}
Now I'm just trying to display the information on my template but I'm struggling. My code for the template looks like:
{% if landing_dict.ingredients %}
<hr>
{% for ingredient in landing_dict.ingredients %}
{{ ingredient }}
{% endfor %}
Print {{ landing_dict.recipe_name }}
{% else %}
Please search for an ingredient below
{% endif %}
It just shows me '0' on my template?
I also tried:
{% for ingredient in landing_dict.ingredients %}
{{ ingredient.cost }}
{% endfor %}
This doesn't even display a result.
I thought perhaps I need to iterate one level deeper so tried this:
{% if landing_dict.ingredients %}
<hr>
{% for ingredient in landing_dict.ingredients %}
{% for field in ingredient %}
{{ field }}
{% endfor %}
{% endfor %}
Print {{ landing_dict.recipe_name }}
{% else %}
Please search for an ingredient below
{% endif %}
But this doesn't display anything.
What am I doing wrong?
Lets say your data is -
data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }
You can use the data.items() method to get the dictionary elements. Note, in django templates we do NOT put (). Also some users mentioned values[0] does not work, if that is the case then try values.items.
<table>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
{% for key, values in data.items %}
<tr>
<td>{{key}}</td>
{% for v in values[0] %}
<td>{{v}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
Am pretty sure you can extend this logic to your specific dict.
To iterate over dict keys in a sorted order - First we sort in python then iterate & render in django template.
return render_to_response('some_page.html', {'data': sorted(data.items())})
In template file:
{% for key, value in data %}
<tr>
<td> Key: {{ key }} </td>
<td> Value: {{ value }} </td>
</tr>
{% endfor %}
This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to
ask it and then answer it, so will just put it here.
This is for the following query:
data = Leaderboard.objects.filter(id=custom_user.id).values(
'value1',
'value2',
'value3')
In template:
{% for dictionary in data %}
{% for key, value in dictionary.items %}
<p>{{ key }} : {{ value }}</p>
{% endfor %}
{% endfor %}
If you pass a variable data (dictionary type) as context to a template, then you code should be:
{% for key, value in data.items %}
<p>{{ key }} : {{ value }}</p>
{% endfor %}
I am thankful for the above answers pointing me in the right direction. From them I made an example for myself to understand it better. I am hoping this example will help you see the double dictionary action more easily and also help when you have more complex data structures.
In the views.py:
bigd = {}
bigd['home'] = {'a': [1, 2] , 'b': [3, 4] ,'c': [5,6] }
bigd['work'] = {'e': [1, 2] , 'd': [3, 4] ,'f': [5,6] }
context['bigd'] = bigd
In the template.html:
{% for bigkey, bigvalue in bigd.items %}
<b>{{ bigkey }}</b> <br>
{% for key, value in bigvalue.items %}
key:{{ key }} <br>
----values: {{ value.0}}, {{value.1 }}<br>
{% endfor %}
<br>
{% endfor %}
Notice the list in the second dictionary is accessed by the index in the list.
Result in browser is something like:

Categories