Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two dimensional associative array in Python

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.

like image 382
shreyasva Avatar asked Jul 14 '11 16:07

shreyasva


1 Answers

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})
>>> 
like image 84
SingleNegationElimination Avatar answered Oct 07 '22 23:10

SingleNegationElimination