Python dictlist: Difference between revisions
From Wildsong
Jump to navigationJump to search
Brian Wilson (talk | contribs) Created page with "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], } https://docs.pyth..." |
Brian Wilson (talk | contribs) mNo edit summary |
||
Line 8: | Line 8: | ||
https://docs.python.org/2/library/collections.html#collections.defaultdict | The official documentation is here: https://docs.python.org/2/library/collections.html#collections.defaultdict | ||
I do this: | |||
<pre> | |||
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) | |||
</pre> |
Latest revision as of 23:36, 2 July 2018
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)