I am trying to store arrays in multiple key groups to generate group-wise summaries. I thought dict of dicts may be a solution. Based on this answer, I tried to make a dict of dict. Here is the code
import numpy
from collections import defaultdict
s1 = numpy.array([[1L, 'B', 4],
[1L, 'A', 3],
[1L, 'B', 10],
[1L, 'A', 0.0],
[2L, 'A', 11],
[2L, 'B', 13],
[2L, 'B', 1],
[2L, 'A', 6]], dtype=object)
def make_dict():
return defaultdict(make_dict)
d = defaultdict(make_dict)
for x in s1:
d[x[0]][x[1]] = x[2]
So, d[1]['B'] gives 10 while I was expecting [4,10]. Looks like d is picking up the last combination. Is there a way to append all the values that fit a particular key combination? I thought defaultdict should take care of this. Where am I going wrong? Is there any other solution to this? I can easily do it in pandas and I love the library. But I am requiring an non-pandas solution.
Update The question was answered (@juanpa.arrivillaga ) but looks like my example data was inadequate. How about if we had the following as data?
s1 = numpy.array([
[1L, 'B', 4,3],
[1L, 'A', 3,5],
[1L, 'B', 10,23],
[2L, 'A', 11,1],
[2L, 'B', 1,8],
[2L, 'A', 6,23]
], dtype=object)
We may not be able to use defaultdict(lambda:defaultdict(list)) as the dictionary container. How to extend the solution to include and append 2D-array instead of list. I expect d[1]['A'] should give me [[3,5],[11,1]]