I have a set() with terms like 'A' 'B' 'C'. I want a 2-d associative array so that i can perform an operation like d['A']['B'] += 1 . What is the pythonic way of doing this, I was thinking a dicts of dicts. Is there a better way.
There are two obvious solutions: One, use defaultdict to nest a dict automatically inside another dict
>>> d = collections.defaultdict(dict)
>>> d['a']['b'] = 'abc'
>>> d
defaultdict(<type 'dict'>, {'a': {'b': 'abc'}})
>>> 
The other is to just use tuples for your dict keys:
>>> d = {}
>>> d['a','b'] = 'abc'
>>> d
{('a', 'b'): 'abc'}
>>> 
To get the += behavior, substitute a defaultdict(int) for the dicts above:
>>> d = collections.defaultdict(lambda:collections.defaultdict(int))
>>> d['a']['b'] += 1
>>> d
defaultdict(<function <lambda> at 0x18d31b8>, {'a': defaultdict(<type 'int'>, {'b': 1})})
>>> 
>>> d = collections.defaultdict(int)
>>> d['a','b'] += 1
>>> d
defaultdict(<type 'int'>, {('a', 'b'): 1})
>>> 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With