How to get the item index or number along with the key, value in dict

For the dictionary, I want to track the number of elements that have been analyzed. Is there a better way to do this compared to what is shown below?

count = 0 for key,value in my_dict.iteritems(): count += 1 print key,value, count 
+6
source share
1 answer

You can use the enumerate() function:

 for count, (key, value) in enumerate(my_dict.iteritems(), 1): print key, value, count 

enumerate() effectively adds a counter to the iterator that you are looping. In the above example, I will tell enumerate() to start counting from 1 according to your example; the default value should start at 0.

Demo:

 >>> somedict = {'foo': 'bar', 42: 'Life, the Universe and Everything', 'monty': 'python'} >>> for count, (key, value) in enumerate(somedict.iteritems(), 1): ... print key, value, count ... 42 Life, the Universe and Everything 1 foo bar 2 monty python 3 
+21
source

Source: https://habr.com/ru/post/946734/


All Articles