I’m creating a defaultdict from an array of arrays:
>>> array = [['Aaron','1','2'],['Ben','3','4']]
>>> d = defaultdict(list)
>>> for i in array:
... d[i[0]].append({"num1":i[1],"num2":i[2]})
My expected outcome is:
>>> d
defaultdict(<type 'list'>, {'Aaron': {'num1': '1', 'num2': '2'},
'Ben': {'num1': '3', 'num2': '4'}})
But my outcome is:
>>> d
defaultdict(<type 'list'>, {'Aaron': [{'num1': '1', 'num2': '2'}],
'Ben': [{'num1': '3', 'num2': '4'}]})
It is as if defaultdict is trying to keep my values in an array because that is the source list!
Anyone know what’s going on here and how I can get my expected outcome?
When you call this:
It means that if you attempt to access
d['someKey']and it does not exist,d['someKey']is initialized by callinglist()with no arguments. So you end up with an empty list, which you then append your dictionary to. You probably want this instead:and then this: