Monday, January 12, 2015

Python: defaultdict(list) Dictionary of Lists

Most of the time, when you need to work on large data, you'll have to use some dictionaries in Python. Dictionaries of lists are very useful to store large data in very organized way. You can always initiate them by initiating empty lists inside an empty dictionary but when you don't know how many of them you'll end up with and if you want an easier option, use defaultdict(list). You just need to import it, first:
from collections import defaultdict
And then initiate anywhere:
dict = defaultdict(list)
You can always collect data in this way:
dict["some_id"].append("some_value")

No comments: