简体   繁体   中英

Error for Counter variable in for loop with enumerate

I keep getting a ValueError when trying to add a variable called counter into the for loop. When the counter variable and the enumerate tag is removed, the program works fine, but when it is added the program breaks down.

Here is the code where the error occurs:

SStrats = {'RSI': OrderedDict([('Exchange', 'Bybit'), ('AccountName', 'Account1'), ('StrategyName', 'RSI'), ('Script', 'MomentumStrats'), ('StratStatus', 'ACTIVE')]), 'ROCR100': OrderedDict([('Exchange', 'Bybit'), ('AccountName', 'Account1'), ('StrategyName', 'ROCR100'), ('Script', 'MomentumStrats'), ('StratStatus', 'ACTIV
E')]), 'MOM': OrderedDict([('Exchange', 'Bybit'), ('AccountName', 'Account1'), ('StrategyName', 'MOM'), ('Script', 'MomentumStrats'), ('StratStatus', 'ACTIVE')])}

for counter,strategy,Status in enumerate(SStrats.items()):
    print("Account: ", Acc_name, "Strategy: ", strategy, "Strat Status:", Status["StratStatus"], "counter", counter)

The result of this code:

ValueError: not enough values to unpack (expected 3, got 2)

You get a tuple (pair) with an int and a tuple (the key-value-pair from the OrderedDict ), not a triple.

You can unpack the values like this:

for counter, (strategy, Status) in enumerate(SStrats.items()):
    print("Account: ", Acc_name, "Strategy: ", strategy, "Strat Status:", Status["StratStatus"], "counter", counter)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM