You can use zip()
to loop through the two lists simultaneously. If you don't need the dict to be in order, it's much easier to use collections.defaultdict()
than a normal dictionary:
import collections
titles = ['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']
pages = [1, 2, 3]
d = collections.defaultdict(list)
for title, page in zip(titles, pages):
for word in title.split():
d[word].append(page)
Although since your pages
is just a list of subsequent numbers, it's probably better to use enumerate
so you don't have to update the pages
list every time you make changes:
import collections
titles = ['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']
d = collections.defaultdict(list)
for page, title in enumerate(titles, start=1):
for word in title.split():
d[word].append(page)
Now if you do need the dict to be in order, you can use OrderedDict
combined with @Keatinge's answer:
import collections
titles = ['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']
d = collections.OrderedDict()
for title, page in enumerate(titles, start=1):
for word in title.split():
if word not in d:
d[word] = [page]
else:
d[word].append(page)
Or if you only need the output to be sorted, use the earlier defaultdict
solution and throw in sorted()
when outputting the values:
for key in sorted(d.keys()):
print('{0}: {1}'.format(key, d[key]))
Finally, you could use an OrderedDefaultDict
, but most would argue that this is a bit of an overkill for such a simple program.