Elegantly making a dictionary of lists

In Python I sometimes want to make a dictionary of lists. So usually I would write something like:


mydic = {}
for something in somethingelse:
mydic[somekey].append(something)

This however will not work, if somekey did not exist so far, because it will raise an exception. But there is help! You can use a collection:


import collections
mydic = collections.defaultdic(list)
for something in somethingelse:
mydic[somekey].append(something)

Leave a Reply

Your email address will not be published.