-2

I have a list of dictionaries that I want to iterate over, but I only want to iterate up until a specific index rather that the entirety of the list.

My code:

new_hero_list = []
for hero in hero_data:
        dict = {key: value for key, value in hero.items() if key in keys}
        # some stuff ...
        new_hero_list.append(dict)

The list hero_data contains 100+ dictionaries, but in most cases I only want to iterate over the first nth indexes, such as 3. How could I achieve this?

Jake Jackson
  • 1,055
  • 1
  • 12
  • 34
  • 1
    Does this answer your question? [Accessing the index in 'for' loops?](https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops) – Mike Scotty Sep 17 '21 at 14:35
  • 3
    `for hero in hero_data[:n]`? – gold_cy Sep 17 '21 at 14:35
  • 1
    You need to use the `range()` function in your loop. – Rashid 'Lee' Ibrahim Sep 17 '21 at 14:36
  • @gold_cy Thanks, that is what I was looking for. I was considering a counter after posting, but your answer is much cleaner. – Jake Jackson Sep 17 '21 at 14:37
  • 2
    @Rashid'Lee'Ibrahim ``enumerate`` is more pythonic than ``range`` - unless you have to support Python 2.2 or older – Mike Scotty Sep 17 '21 at 14:37
  • @MikeScotty I'd say depends on how it's used. Would you somehow use `enumerate` instead of `range` [here](https://tio.run/##VYzBCoMwEETv@xV7MwHpxUsR/JJSwrZZNSCbZQ0U@/Op2pNzfG9mdCtzlu6uVuvMlkOkQjhgQ6935LEBEP6E0yxpLbt5PGHMhqHFg2IS/CZ1RjKx6/yfni@@B9xz2d9IlSW6A3gAtSTFXRq@1h8)? – no comment Sep 17 '21 at 14:40
  • 1
    @Rashid'Lee'Ibrahim wrapping it in ``zip`` is actually a nice idea and saves you the ``if(...): break`` inside the loop. When you suggested to use ``range`` I thought you meant it like [this](https://stackoverflow.com/a/522569/4349415) where you then access the item by index and you'd still have to use an ``if(...): break`` to exit the loop. – Mike Scotty Sep 17 '21 at 14:47
  • 1
    I found a dupe that uses zip+range: https://stackoverflow.com/questions/36106712/how-can-i-limit-iterations-of-a-loop-in-python – Mike Scotty Sep 17 '21 at 14:50
  • @MikeScotty I am actually doing something similar in another screen right now that requires me to compare the list of dicts to another list and I'm working on a zip with range solution. I didn't expand on the idea because I'm still working on it. – Rashid 'Lee' Ibrahim Sep 17 '21 at 14:56

1 Answers1

1

one way you can use is enmerator to track the count of the iteration and you can break the for loop when your nth iteration is met

new_hero_list = []
for index, (key, value) in enumerate(hero_data.items()):
    dict = {key: value for key, value in hero.items() if key in keys}
    # some stuff ...
    new_hero_list.append(dict)
    if index == n:
      break