enumerate() for dictionary in python

前端 未结 11 1229
走了就别回头了
走了就别回头了 2020-12-08 05:55

I know we use enumerate for iterating a list but I tried it in a dictionary and it didn\'t give an error.

CODE:

enumm = {0: 1, 1: 2, 2:          


        
11条回答
  •  半阙折子戏
    2020-12-08 06:24

    enumerate() when working on list actually gives the index and the value of the items inside the list. For example:

    l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    for i, j in enumerate(list):
        print(i, j)
    

    gives

    0 1
    1 2
    2 3
    3 4
    4 5
    5 6
    6 7
    7 8
    8 9
    

    where the first column denotes the index of the item and 2nd column denotes the items itself.

    In a dictionary

    enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
    for i, j in enumerate(enumm):
        print(i, j)
    

    it gives the output

    0 0
    1 1
    2 2
    3 4
    4 5
    5 6
    6 7
    

    where the first column gives the index of the key:value pairs and the second column denotes the keys of the dictionary enumm.

    So if you want the first column to be the keys and second columns as values, better try out dict.iteritems()(Python 2) or dict.items() (Python 3)

    for i, j in enumm.items():
        print(i, j)
    

    output

    0 1
    1 2
    2 3
    4 4
    5 5
    6 6
    7 7
    

    Voila

提交回复
热议问题