Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-02-14 13:32:31

0001 # Copyright (C) 2014 Colin Bernet
0002 # https://github.com/cbernet/heppy/blob/master/LICENSE
0003 
0004 class diclist( list ):
0005     '''list with an internal dictionary for indexing, 
0006     allowing to keep dictionary elements ordered. 
0007     keys can be everything except an integer.
0008     '''
0009 
0010     def __init__(self):
0011         super( diclist, self).__init__()
0012         # internal dictionary, will contain key -> index in list
0013         self.dico = {}
0014 
0015     def add( self, key, value ):
0016         if isinstance(key, (int, long)):
0017             raise ValueError("key cannot be an integer")
0018         if key in self.dico:
0019             raise ValueError("key '{key}' already exists".format(key=key) )
0020         self.dico[key] = len(self)
0021         self.append(value)
0022 
0023     def __getitem__(self, index):
0024         '''index can be a dictionary key, or an integer specifying
0025         the rank of the value to be accessed
0026         '''
0027         try:
0028             # if index is an integer (the rank), use the list.
0029             return super(diclist, self).__getitem__(index)
0030         except (TypeError, ValueError):
0031             # else it's the dictionary key.
0032             # use the internal dictionary to get the index,
0033             # and return the corresponding value from the list
0034             return super(diclist, self).__getitem__( self.dico[index] )
0035 
0036     def __setitem__(self, index, value):
0037         '''These functions are quite risky...'''
0038         try:
0039             return super(diclist, self).__setitem__(index, value)
0040         except TypeError as ValueError:
0041             return super(diclist, self).__setitem__( self.dico[index], value )
0042 
0043 
0044