3

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!

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Oh, come on. That's just not fair. Promise me that when you hit 100k you'll give the rest of us at least thirty seconds worth of handicap!
Amazing! thank you sir for the extremely fast response!... I'll accept the answer once the minimum 15 mins have passed. :)
@ToOsIK: I am in to hurry; perhaps others can think of something that is better still, give them a chance too! :-)
@DSM: I'll be gone a large part of tomorrow... try and spot the lulls! :-P
@DSM -- Do you think we could convince the moderators that Martijn has somehow hacked SO so that he gets the chance to see every question before other users -- Or that he's some kind of really smart and useful non-spam-bot? (Seriously -- I don't think I can even type that quickly)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.