I have a dictionary that I would like to update with items from a list. The list has items that are scraped from a website. How can I add the list items to the dictionary along with individual key names?
I am stumped on how to suffix the Copy
key with a serialized sequence; additionally I would like all scraped items to be logged not just the last item in the list.
Note: Scraped items can be prefixed with any string
for item in scraped_items:
dict['Copy '] = item # Copy key should include a number suffix, e.g., 'Copy 0, Copy 1' and log all scraped items
# current output: {'locale': 'some place', 'Copy': <p>Second copy block</p>, 'title': 'some site'}
Scraped items:
[<p>First copy block</p>, <p>Second copy block</p>]
<type 'list'>
Current dictionary:
{
"locale": "some place",
"title": "some site"
}
Expected dictionary:
{
"locale": "some place",
"title": "some site",
"Copy 0": "<p>First copy block</p>",
"Copy 1": "<p>Second copy block</p>"
}
CodePudding user response:
You could loop through the indices of the list instead of the items themselves.
for i in range(len(scraped_items)):
dict[f'Copy {i}'] = scraped_items[i]
CodePudding user response:
You can try using enumerate
as well
for index,val in enumerate(scraped_items):
dic[f'Copy {index}'] = val
{'locale': 'some place',
'title': 'some site',
'Copy 0': '<p>First copy block</p>',
'Copy 1': '<p>Second copy block</p>'}