Search code examples
python-3.xdictionarybreakenumerate

Break is not activated inside a for loop in Python


I want to print the first 10 key-value pairs from the dictionary word_index and I wrote this code:

for key, value in enumerate(word_index):
    count = 0
    if count <10:
        print(f'key {key} : value: {value}')
        count = count + 1
    else:
        break

enter image description here

As you can see the break is not activated. Why is that? What I should change in the code?


Solution

  • You need to move the declaration of count before the for loop. It is reset to 0 at each iteration.

    As a side note (I don't have enough reputation to comment) the for loop is probably not doing what you want. You named your variables key and value, which makes me believe that you want to iterate over the entries (key and value pairs) of the dictionary. To achieve that you should write:

    for k,v in word_index.items():
      // omitted
    

    What enumerate() does is to return an index that starts from 0 and it is incremented at each iteration. So the in your code, key is actually an index and value is the dictionary's key!

    If you actually wanted to iterate over the keys and associate an index to each key, you should rename your variable to something more correct, for example index and key.

    I recommend to spend some time studying Python, it will save you lots of debugging time.