AlexW
AlexW

Reputation: 2587

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

Upvotes: 1

Views: 366

Answers (3)

Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 1767

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 %}

Upvotes: 0

Rakesh
Rakesh

Reputation: 82765

I believe you need.

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

Upvotes: 2

Manan M.
Manan M.

Reputation: 1394

I think you have to write your <h3> tag as below...

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

Upvotes: 0

Related Questions