KeyError looping through multiple values per key

This question already has an answer here:

  • Iterating over dictionaries using 'for' loops 12 answers

  • T is the key, so you should iterate with 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)
    

    If you use for T in instruments.items() , T becomes a tuple of (key, value) . When you then look for instruments[T] , there's no such key in the dict.

    You could also unpack the value tuple directly if you insist on using items() :

    for t, (par, coup, price, freq) in instruments.items():
        if coup == 0:
            print(t)
    

    It outputs:

    0.25
    0.5
    
    链接地址: http://www.djcxy.com/p/30380.html

    上一篇: 我如何跳过`foreach`循环的迭代?

    下一篇: KeyError循环每个键的多个值