2

My dictionary looks some think like this.

allCurrencies = {
    'AUD': ['Australian Dollar', 'au'],
    'GBP': ['British Pound', 'gb'],
    'CAD': ['Canadian Dollar', 'ca'],
    'INR': ['Indian Rupee', 'in'],
    'JPY': ['Japanese Yen', 'jp'],
    'RUB': ['Russian Ruble', 'ru'],
    'SGD': ['Singapore Dollar', 'sg'],
    'CHF': ['Swiss Franc', 'ch'],
    'USD': ['US Dollar', 'us']
}

and my array contains this:

commonCurrencies = ['USD', 'EUR', 'GBP', 'JPY']

My main goal is to iterate commonCurrencies and use it as a key for the dictionary allCurrencies.

My django template currently look like this:

<tr>
    {% for sym in commonCurrencies %}
        <td>{{allCurrencies.sym.0}}<td>
    {% endfor %}
</tr>

But it does not seem to work. What am I doing wrong. Thanks

falsetru
  • 357,413
  • 63
  • 732
  • 636
hammerhead
  • 35
  • 1
  • 6

1 Answers1

2

AFAIK, there's no builtin filter, tag that allow you to get item from dictionary dynamically. You'd better filter the value in views, and pass it to template. Otherwise, you need to make custom template tag to get value dictionary value dynamically.

>>> allCurrencies = {
...     'AUD': ['Australian Dollar', 'au'],
...     'GBP': ['British Pound', 'gb'],
...     'CAD': ['Canadian Dollar', 'ca'],
...     'INR': ['Indian Rupee', 'in'],
...     'JPY': ['Japanese Yen', 'jp'],
...     'RUB': ['Russian Ruble', 'ru'],
...     'SGD': ['Singapore Dollar', 'sg'],
...     'CHF': ['Swiss Franc', 'ch'],
...     'USD': ['US Dollar', 'us']
... }
>>>
>>> commonCurrencies = ['USD', 'EUR', 'GBP', 'JPY']
>>>
>>> currencies = {cur: allCurrencies[cur] for cur in commonCurrencies
                  if cur in allCurrencies}
>>>
>>> currencies
{'JPY': ['Japanese Yen', 'jp'],
 'USD': ['US Dollar', 'us'],
 'GBP': ['British Pound', 'gb']}

BTW, there's no EUR entry in the allCurrencies dictionary.

Community
  • 1
  • 1
falsetru
  • 357,413
  • 63
  • 732
  • 636