pythonloopsdictionaryenumerate

How to iterate `dict` with `enumerate` and unpack the index, key, and value along with iteration


How to iterate a dict with enumerate such that I could unpack the index, key and value at the time of iteration?

Something like:

for i, (k, v) in enumerate(mydict):
    # some stuff

I want to iterate through the keys and values in a dictionary called mydict and count them, so I know when I'm on the last pair.


Solution

  • Instead of using mydict, you should be using mydict.items() with enumerate as:

    for i, (k, v) in enumerate(mydict.items()):
        # your stuff
    

    Sample example:

    mydict = {1: 'a', 2: 'b'}
    for i, (k, v) in enumerate(mydict.items()):
        print("index: {}, key: {}, value: {}".format(i, k, v))
    
    # which will print:
    # -----------------
    # index: 0, key: 1, value: a
    # index: 1, key: 2, value: b
    

    Explanation: