如何在使用该密钥时评估dict中特定键的值
在字符串变量(currency
)中获取基础值?我现在正在尝试的是:
offer = {'USD': [0.12, 0.15, 0.20, 0,50]}
currency = ['USD']
print(offer[currency])
我想要那个
>>> [0.12, 0.15, 0.20, 0,50]
我缺少任何功能或方法吗?
答案 0 :(得分:2)
您可以迭代所有货币,并在字典上执行.get
:
In [75]: offer = {'USD': [0.12, 0.15, 0.20, 0,50]}
...: currency = ['USD']
...:
In [76]: for c in currency:
...: print(offer.get(c, []))
...:
[0.12, 0.15, 0.2, 0, 50]
可替换地;
In [77]: for c in currency:
...: print(offer[c]) # if all currency will exist within the dict
...:
[0.12, 0.15, 0.2, 0, 50]
答案 1 :(得分:2)
只需使用简单的字符串即可获得密钥,无需使用括号:
offer = {'USD': [0.12, 0.15, 0.20, 0,50]}
currency = 'USD'
print(offer[currency])
答案 2 :(得分:0)
你可以使用它。
offer = {'USD': [0.12, 0.15, 0.20, 0,50]}
currency = offer['USD']
print(currency)