我的字典看起来有些像这样。
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/