Python dictlist

From Wildsong
Revision as of 23:36, 2 July 2018 by Brian Wilson (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

This is a common pattern that I use, I need a dictionary that has a list for each of its values, like this

d = {
   "a" : [1,2,3],
   "b" : [3,4,5],
}


The official documentation is here: https://docs.python.org/2/library/collections.html#collections.defaultdict

I do this:

from collections import defaultdict
dict_list = defaultdict(list)
 
dict_list["a"].append(1)
dict_list["a"].append(2)
dict_list["a"].append(3)

dict_list["b"].append(3)
dict_list["b"].append(4)
dict_list["b"].append(5)