简体   繁体   中英

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.

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})
>>> 

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM