迭代列表并将该值用于字典键

时间:2016-10-16 14:55:08

标签: python django list dictionary django-templates

我的字典看起来有点像这样。

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']

我的主要目标是迭代commonCurrencies并将其用作字典allCurrencies的密钥。

我的django模板目前看起来像这样:

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

但它似乎不起作用。我究竟做错了什么。感谢

1 个答案:

答案 0 :(得分:2)

AFAIK,没有内置过滤器,标签允许您动态地从字典中获取项目。您最好过滤视图中的值,并将其传递给模板。 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']}

顺便说一句,EUR词典中没有allCurrencies条目。