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

后端 未结 1 1792
梦如初夏
梦如初夏 2020-12-13 17:02

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

Something like:



        
相关标签:
1条回答
  • 2020-12-13 17:38

    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
    

    Explanations:

    • enumerate returns an iterator object which contains tuples in the format: [(index, list_element), ...]
    • dict.items() returns an iterator object (in Python 3.x. It returns list in Python 2.7) in the format: [(key, value), ...]
    • On combining together, enumerate(dict.items()) will return an iterator object containing tuples in the format: [(index, (key, value)), ...]
    0 讨论(0)
提交回复
热议问题