[Tutor] Question about Dictionaries

Emile van Sebille emile at fenx.com
Tue Aug 17 02:20:01 CEST 2010


On 8/16/2010 4:12 PM Huy Ton That said...
> What do you mean by subclass?
>
<snip>
>
> If you need repeated access such that iterating over a large dict frequently
> impacts performance, you could subclass dict and maintain a second index
> allowing instant access to the keys associated with a specific value.
>
> HTH,
>
> Emile
>


Something along these lines:

class myDict(dict):
     def __init__(self):
         self.altKeys = {}
     def __setitem__(self,ky,val):
         self.altKeys[val]=ky
         return dict.__setitem__(self, ky,val)
     def lookup(self,ky):
         return self.altKeys[ky]


a = myDict()

a[1] = 111
a[2] = 222
a[3] = 333

a[3]

a.lookup(333)


Emile



More information about the Tutor mailing list