enumerate() for dictionary in python

前端 未结 11 1236
走了就别回头了
走了就别回头了 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:28

    1. Iterating over a Python dict means to iterate over its keys exactly the same way as with dict.keys()
    2. The order of the keys is determined by the implementation code and you cannot expect some specific order:

      Keys and values are iterated over in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.

    That's why you see the indices 0 to 7 in the first column. They are produced by enumerate and are always in the correct order. Further you see the dict's keys 0 to 7 in the second column. They are not sorted.

提交回复
热议问题