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!
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.
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