简体   繁体   中英

Django template - iterate a list of tuples, each tuple is a string, dictionary

I have a dictionary that has been turned into a sorted list, which creates the below:

monthly_spend_provider = sorted(monthly_spend_provider.items(), key=lambda item: item[1]['cost'], reverse=True)
monthly_spend_provider
[
('PROVIDER A', {'cost': Decimal('10000'), 'symbol': '£'}), 
('PROVIDER B', {'cost': Decimal('9000'), 'symbol': '$'}), 
('PROVIDER C', {'cost': Decimal('8000'), 'symbol': '$'}), 
('PROVIDER D', {'cost': Decimal('7000'), 'symbol': '£'}), 
]

now im trying to access the data in the tuples in a Django template thus far unsucessfully.

I thought the below would of worked but it hasn't

{% for provider in monthly_provider_country %}
    {% for data in provider %}
    <h3>{{ provider }} {{ data.symbol }} {{ data.cost|currency }}</h3>
    {% endfor %}
{% endfor %}

can I do this in a template or is there a way to turn the sorted list back into an easier format to output into a template?

EDIT: original dictionary

>>> monthly_spend_provider
{
    'PROVIDER B': {
        'cost': Decimal('9000'), 'symbol': '$'
        },
    'PROVIDER A': {
        'cost': Decimal('10000'), 'symbol': '£'
        },
    'PROVIDER D': {
        'cost': Decimal('8000'), 'symbol': '$'
        },
    'PROVIDER C': {
        'cost': Decimal('7000'), 'symbol': '£'
        }
}

Thanks

I believe you need.

{% for provider, d in monthly_provider_country %}
    <h3>{{ provider }} {{ d.symbol }} {{ d.cost|currency }}</h3>
{% endfor %}

我认为你必须写你的<h3>标签如下...

<h3>{{ data.0 }} {{ data.1.symbol }} {{ data.1.cost|currency }}</h3>

Try this below:

{% for provider in monthly_provider_country %}
    {% for data in provider %}
    <h3>{{ data[0] }} {{ data[1].symbol }} {{ data[1].cost|currency }}</h3>
    {% endfor %}
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM