Search code examples
pythonloopsfor-loopordereddictionaryiterable-unpacking

Error cannot unpack non-iterable when trying to Iterate over OrderedDict()


I'm trying to iterate over a OrderedDict on python 3.9 but when I'm getting:

for key, value in d: TypeError: cannot unpack non-iterable int object execute the for bucle

Here is my code:

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)

Solution

  • To iterate over a dict's pairs use .items()

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

    Also you seems to have a dict d but then you create another dict d2, check that ;)