开发者

Two dimensional associative array in Python

I have a set() with te开发者_开发问答rms 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})
>>> 


A dict of dict is one way.

An alternative is to simply use a tuple:

d[('A','B')] += 1

As pointed out by TokenMacGuy, the parentheses are optional:

d['A','B'] += 1

Depending on your code, this might simplify things.


Is there any reason not to use a dict of dicts? It does what you want (though note that there's no such thing as ++ in Python), after all.

There's nothing stylistically poor or non-Pythonic about using a dict of dicts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜