2

I have a for loop that goes through two lists and combines them in dictionary. Keys are strings (web page headers) and values are lists (containing links).

Sometimes I get the same key from the loop that already exists in the dictionary. Which is fine. But the value is different (new links) and I'd like to update the key's value in a way where I append the links instead of replacing them.

The code looks something like that below. Note: issue_links is a list of URLs

for index, link in enumerate(issue_links):
    issue_soup = BeautifulSoup(urllib2.urlopen(link))
    image_list = []
    for image in issue_soup.findAll('div', 'mags_thumb_article'):
        issue_name = issue_soup.findAll('h1','top')[0].text
        image_list.append(the_url + image.a['href'])

    download_list[issue_name] = image_list

Currently the new links (image_list) that belong to the same issue_name key get overwritten. I'd like instead to append them. Someone told me to use collections.defaultdict module but I'm not familiar with it.

Note: I'm using enumerate because the index gets printed to the console (not included in the code).

1

2 Answers 2

3

Something like this:

from collections import defaultdict

d = defaultdict(list)

d["a"].append(1)
d["a"].append(2)
d["b"].append(3)

Then:

print(d)
defaultdict(<class 'list'>, {'b': [3], 'a': [1, 2]})
Sign up to request clarification or add additional context in comments.

1 Comment

It always delights me when somebody founds my answers buried in the ice age :)
0
if download_list.has_key(issume_name):
    download_list[issume_name].append(image_list)
else:
    download_list[issume_name] = [image_list]

is it right?If you have the same key, append the list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.