尝试对OrderedDict进行迭代时,错误无法解包不可迭代

问题描述

我正在尝试遍历python 3.9上的OrderedDict,但是当我得到时:

对于键,d中的值: TypeError:无法解压缩不可迭代的int对象,请执行for bucle

这是我的代码:

MAXSIZE = 5
d = dict()

while True:

    candles = api.get_candles(EURUSD,5,1,time.time())

    candleOpen = float(candles[0]['open'])
    candleClose = float(candles[0]['close'])

    candleID = candles[0]['id']
                
    if candleOpen < candleClose:            
        d2 = {candleID: 'A'}

    elif candleOpen > candleClose:          
        d2 = {candleID: 'B'}
        
    else:
        d2 = {candleID: 'C'}            
    
    if len(d) == MAXSIZE:
        for key,value in d:
            print(key)

解决方法

要遍历字典对,请使用.items()

# print(type(d)) to ensure you have a dict
for key,value in d.items():
    print(key)

您似乎也有一个字典d,但是随后您创建了另一个字典d2,请检查;)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...