Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2 Dimension Array (Matrix) with string indices

In Python (2.7), is there a native 2 dimensional data structure that can be accessed through string based indices?

I know you can have a dictionary that can be accessed with a string index, for example:

>>> dic = dict()
>>> dic['grumpy'] = 'cat'
>>> print(dict['grumpy'])
'cat'

But what I would like is a data structure that can be accessed like:

>>> dic['grumpy']['frumpy'] = 'cat'
>>> print(dict['grumpy']['frumpy'])
'cat'

Array seems to be a no-go since it only allows integer based access... any suggestions? Thanks!

like image 577
ToOsIK Avatar asked Apr 20 '26 10:04

ToOsIK


1 Answers

Use a defaultdict:

from collections import defaultdict

nesteddict = defaultdict(dict)

nesteddict['abc']['spam'] = 'ham'

Note that what you describe is a simple nested structure; you can also build it without using defaultdict but that class makes it all the easier to do so.

like image 157
Martijn Pieters Avatar answered Apr 23 '26 00:04

Martijn Pieters