How to store the reference of a dictionary element ?

Alfredo P. Ricafort alpot at mylinuxsite.com
Fri Dec 20 21:31:29 EST 2002


Hi,

First of all, thanks to everyone who replied, especially for those
people who took time to write codes.

Using the ideas and suggestions of others, I think of a solution that
fits my requirement.  The idea is to use handler, or **ptr(pointer to
pointer). So in Python, I used List as my handler. 

Here's the code:

# this is my custom list
class mylist(list):
      def __setitem__(self,k,v):
          self[k]=v

# this is my custom dict
class mydict(dict):
      def __setitem__(self,k,v): 
          if self.has_key(k):            
             item=self[k]
             item.remove(item[0])
             item.append(v)
          else:
             item=mylist() 
             item.append(v)
          if isinstance(v,mylist):
             item=v
          dict.__setitem__(self,k,item)


For example, if the menu structure is like this:

aMenu={'key':[label,help,ptrToParent]} 

then storing data is simply like this:

#  Storing 3 records, with the 2 records pointing to 1 parent
>>> aMenu=mydict()
>>> aMenu['/File']=['&File','File Help',None]         <---- parent
>>> aMenu['/File/New']=['&New','New Help', aMenu['/File']]
>>> aMenu['/File/Open']=['&Open','Open Help',aMenu['/File']]

# The 2 children points to the parent correctly
>>> aMenu['/File/New']
[['&New', 'New Help', [['&File', 'File Help', None]]]]
>>> aMenu['/File/Open']
[['&Open', 'Open Help', [['&File', 'File Help', None]]]]

# Changing the 'help' description of the parent by replacing the whole
record. Children can still see the change
>>> aMenu['/File']=['&File','Help on File',None]

>>> aMenu['/File/New']
[['&New', 'New Help', [['&File', 'Help on File', None]]]]
>>> aMenu['/File/Open']
[['&Open', 'Open Help', [['&File', 'Help on File', None]]]]

# unlinking one of the children
>>> aMenu['/File/New'][0][2]=None
>>> aMenu['/File/New']
[['&New', 'New Help', None]]

>>> aMenu['/File/Open']
[['&Open', 'Open Help', [['&File', 'Help on File', None]]]]

# changing the 'help' description of the parent. The remaining child
still sees the changes.
>>> aMenu['/File'][0][1]='Back to File Help'
>>> aMenu['/File/Open']
[['&Open', 'Open Help', [['&File', 'Back to File Help', None]]]] 

>>> aMenu['/File/New']
[['&New', 'New Help', None]]


But this solution suffers from the need to subscript everything with [0]
to get to the items. I still finding ways to overcome that.

AL






More information about the Python-list mailing list