2

I have a list that contains dictionary's and I want to add every third entry in that list into a new one The list looks like this:

result = [{"link": "example.com", "text": "Some description"}, {"link": "example2.com", "text": "lorem ipsum"}] ...

Right now the loop I have looks like this:

for i in range(0, len(list), 3):
    cleanresults.extend(list[i])

but instead of copying the whole list it only adds the keys

["link", "text", "link", "text"]

What did I do wrong?

BloodViolet
  • 67
  • 2
  • 10

2 Answers2

6

You want to append, not extend:

for i in range(0, len(list), 3):
    cleanresults.append(list[i])

Extending adds the contained elements from the object you passed in; when you iterate over a dictionary you get keys, so those are then added to the cleanresults list, not the dictionary itself.

More cleanly, you could just create a copy of the original list taking every 3rd element with a slice:

cleanresults = list[::3]

If you didn't want a copy, but only needed to access every third element while iterating, you could also use an itertools.islice() object:

from itertools import islice

for every_third in islice(list, 0, None, 3):
    # do something with every third dictionary.
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
4

You can try this:

result = [{"link": "example.com", "text": "Some description"}, {"link": "example2.com", "text": "lorem ipsum"}] ...

new_result = result[::3] #this list slicing will take every third element in the result list

Output:

[{'text': 'Some description', 'link': 'example.com'}]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102