views:

95

answers:

4

Solaris python 2.4.3:

from collections import defaultdict 

does not exist..

Please advise what could be an alternative to use multi-level dictionaries:

dictOut['1']['exec'] = 'shell1.sh'
dictOut['1']['onfailure'] = 'continue'
...
dictOut['2']['exec'] = 'shell2.sh'
dictOut['2']['onfailure'] = stop'

many thanks applom

+2  A: 

setdefault?

dictOut.setdefault('1', {})['exec'] = 'shell1.sh'
Amber
Note that this requires you to use `setdefault` every time you're using a new top-level key.
Michael Mior
+2  A: 

Answered with looks-like-it-works code within the last 24 hours (found by searching for "defaultdict", choose "newest" or "active" order)

John Machin
@Imran, I'll leave it up to John Machin, but actually displaying my code in his post implies a stronger endorsement than just linking to it which he may not actually feel. Also, It's not _entirely_ clear that he was referring specifically to my code as there was another answer on the thread and he didn't link specifically to mine. Of course if he wants it in his post, he's welcome to use it.
aaronasterling
I think he was specific enough, as there was only 2 answers and in "newest" or "active" order your answer came on top.
Imran
@Imran: The idea of an edit is NOT to change the whole tenor of the answer, which was to try to give a clue to the OP about how to find things out for himself. "Looks like it works" is a not-unreasonable endorsement. Newest/active is an ordering of all matching questions, not just of answers to the question that Aaron answered.
John Machin
+2  A: 

As an alternative to setdefault, if you want extra level of dictionary goodness, try

class MultiDict(dict):
    def __getitem__(self, item):
        if item not in self.iterkeys():
            self[item] = MultiDict()

        return super(MultiDict, self).__getitem__(item)
Michael Mior
@Aaron I just decided to switch to use `setdefault` for that who function since it gets the job done. (I'm not really sure why I had that `new=` in there...)
Michael Mior
Good point. This is what happens to me past 1am. Think I need to head to bed. Fixed up...I think. Let me know if you see any problems :)
Michael Mior
I thought the same thing, but I didn't initially see how to do that correctly. Updated the answer again.
Michael Mior
A: 

I just wonder why not to use single level dict with tuple as hash key?

Tony Veijalainen
because that imposes the bookkeeping of tracking which tuples have been defined as keys on the client code which is silly in the presence of clean and robust alternatives such as that in Michael Mior's answer.
aaronasterling
Hi,apology for not responding - I did not have access to the box during the weekend - Michael Mior's suggestion was perfect. Thanks - applom
apllom