python - 迭代列表并将该值用作字典键

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

我的主要目标是迭代 commonCurrency 并将其用作字典 allCurrency 的键。

我的 django 模板当前如下所示:

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

但是好像不行。我究竟做错了什么。谢谢

最佳答案

据我所知,没有内置的过滤器、标签可以让您动态地从字典中获取项目。您最好过滤 View 中的值,并将其传递给模板。 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']}

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

关于python - 迭代列表并将该值用作字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40071671/

相关文章:

python - rpy2 加载库失败

python - 如何运行测试 django rest 框架测试?

python - 使用Keras进行图像分类,CNN训练很慢

python - Django REST Framework 中的序列化程序验证顺序

java - jList - 添加元素并显示字符串?

python - 将电子表格编号转换为列字母

python - 使用序列化器作为查询参数验证器是一个好习惯吗?

python - 为什么我的 Django 站点在使用此 URL 解析器检查时不返回 404?

list - 如何在 Dart 中将列表转换为 map

python - 在 Python 中创建具有一定行数和列数的列表