BloodViolet
BloodViolet

Reputation: 67

Adding a dict from a list into another list

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?

Upvotes: 2

Views: 66

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121744

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.

Upvotes: 6

Ajax1234
Ajax1234

Reputation: 71451

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'}]

Upvotes: 4

Related Questions