1

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).

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
user3056783
  • 2,265
  • 1
  • 29
  • 55
  • http://stackoverflow.com/questions/10664856/make-dictionary-with-duplicate-keys-in-python – marsh Mar 09 '15 at 03:03

2 Answers2

2

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]})
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
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.