KeyError 循环遍历每个键的多个值
KeyError looping through multiple values per key
(这个问题可能不同于“使用 'for' 循环遍历字典”,因为我对每个键都有多个条目,而且我也有 'pointing' 到正确的问题)。
有这个空字典:
import .math
instruments = {}
下面的简单方法填充它:
def add_instrument(par, T, coup, price, compounding_freq = 2):
instruments[T] = (par, coup, price, compounding_freq)
add_instrument(100, 0.25, 0., 97.5)
add_instrument(100, 0.5, 0., 94.9)
add_instrument(100, 1.0, 3., 90.)
add_instrument(100, 1.5, 8, 96., 2)
如果我们检查:
instruments.keys()
我们得到:[0.25, 0.5, 1.5, 1.0]
然后我想遍历字典并if coup == 0
,做某些操作,否则做其他事情:
for T in instruments.items():
(par, coupon, price, freq) = instruments[T]
if coupon == 0:
do_something
但是我得到了 #KeyError: (0.25, (100, 0.0, 97.5, 2))
知道为什么以及如何重新安排循环吗? TIA.
编辑:使用下面的答案,BootstrapYieldCurve class 按计划工作,在书 'Mastering Python for Finance',ch5.
T
是关键,因此您应该使用 for T in instruments
:
进行迭代
import math
instruments = {}
def add_instrument(par, T, coup, price, compounding_freq = 2):
instruments[T] = (par, coup, price, compounding_freq)
add_instrument(100, 0.25, 0., 97.5)
add_instrument(100, 0.5, 0., 94.9)
add_instrument(100, 1.0, 3., 90.)
add_instrument(100, 1.5, 8, 96., 2)
for T in instruments:
par, coupon, price, freq = instruments[T]
if coupon == 0:
print(T)
如果你使用for T in instruments.items()
,T
变成了(key, value)
的元组。当您随后查找 instruments[T]
时,字典中没有这样的键。
如果你坚持使用 items()
:
也可以直接解压值元组
for t, (par, coup, price, freq) in instruments.items():
if coup == 0:
print(t)
它输出:
0.25
0.5
(这个问题可能不同于“使用 'for' 循环遍历字典”,因为我对每个键都有多个条目,而且我也有 'pointing' 到正确的问题)。
有这个空字典:
import .math
instruments = {}
下面的简单方法填充它:
def add_instrument(par, T, coup, price, compounding_freq = 2):
instruments[T] = (par, coup, price, compounding_freq)
add_instrument(100, 0.25, 0., 97.5)
add_instrument(100, 0.5, 0., 94.9)
add_instrument(100, 1.0, 3., 90.)
add_instrument(100, 1.5, 8, 96., 2)
如果我们检查:
instruments.keys()
我们得到:[0.25, 0.5, 1.5, 1.0]
然后我想遍历字典并if coup == 0
,做某些操作,否则做其他事情:
for T in instruments.items():
(par, coupon, price, freq) = instruments[T]
if coupon == 0:
do_something
但是我得到了 #KeyError: (0.25, (100, 0.0, 97.5, 2))
知道为什么以及如何重新安排循环吗? TIA.
编辑:使用下面的答案,BootstrapYieldCurve class 按计划工作,在书 'Mastering Python for Finance',ch5.
T
是关键,因此您应该使用 for T in instruments
:
import math
instruments = {}
def add_instrument(par, T, coup, price, compounding_freq = 2):
instruments[T] = (par, coup, price, compounding_freq)
add_instrument(100, 0.25, 0., 97.5)
add_instrument(100, 0.5, 0., 94.9)
add_instrument(100, 1.0, 3., 90.)
add_instrument(100, 1.5, 8, 96., 2)
for T in instruments:
par, coupon, price, freq = instruments[T]
if coupon == 0:
print(T)
如果你使用for T in instruments.items()
,T
变成了(key, value)
的元组。当您随后查找 instruments[T]
时,字典中没有这样的键。
如果你坚持使用 items()
:
for t, (par, coup, price, freq) in instruments.items():
if coup == 0:
print(t)
它输出:
0.25
0.5