【问题标题】:iterate list and use that value for dictionary key [duplicate]迭代列表并将该值用于字典键[重复]
【发布时间】:2017-02-25 13:38:50
【问题描述】:

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

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>

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

【问题讨论】:

标签: python django list dictionary django-templates


【解决方案1】:

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

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

【讨论】:

  • 非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-19
  • 2021-04-05
相关资源
最近更新 更多