On Thu, 10 Mar 2005 18:56:41 +0100, bruno modulix <[EMAIL PROTECTED]> wrote:
>G. Völkl wrote: >> Hello, >> >> I use a dictionary: >> >> phone = {'mike':10,'sue':8,'john':3} >> >> phone['mike'] --> 10 >> >> I want to know who has number 3? >> 3 --> 'john' > >Note that you can have many keys with the same value: >phone = {'mike':10,'sue':8,'john':3, 'jack': 3, 'helen' : 10} > > >> How to get it in the python way ? > >simplest way I could think of in 30': >def key_from_value(aDict, target): > return [key for key, value in aDict.items() if value==target] > >key_from_value(phone, 3) >--> ['john', 'jack'] > >but this is a linear search, so not very efficient if phone is big. >Then you may want to maintain a reversed index: >(here again, simplest way I could think of) > >def rev_index(aDict): > r = {} > for key, value in aDict.items(): > if r.has_key(value): > r[value].append(key) > else: > r[value] = [key] > return r >rev_phone = rev_index(phone) >rev_phone >--> {8: ['sue'], 10: ['helen', 'mike'], 3: ['john', 'jack']} > >{8: ['sue'], 10: ['helen', 'mike'], 3: ['john', 'jack']} > >rev_phone[3] >--> ['john', 'jack'] > >But now you've got another problem : you need to update the reversed >index each time you modify the dictionary... Which would lead to writing >a class extending dict, maintaining a reversed index, and exposing extra >methods to handle this. > Not very tested: ----< twoway.py >-------------------- class Twoway(dict): def __setitem__(self, name, number): dict.__setitem__(self, name, number) self.setdefault(number, []).append(name) def __delitem__(self, name): num = self[name] dict.__delitem__(self, name) self[num].remove(name) if not self[num]: del self[num] def __init__(self, src=None): if src is None: return dict.__init__(self, src) for name, num in self.items(): self.setdefault(num, []).append(name) if __name__ == '__main__': phone = Twoway({'mike':10,'sue':8,'john':3, 'jack': 3, 'helen' : 10}) print 'jack:', phone['jack'] print 'same phone as jack:', phone[phone['jack']] print 'deleting jack ...'; del phone['jack'] print 'john:', phone['john'] print phone ------------------------------------- [13:05] C:\pywk\sovm>py24 twoway.py jack: 3 same phone as jack: ['john', 'jack'] deleting jack ... john: 3 {'mike': 10, 3: ['john'], 8: ['sue'], 10: ['mike', 'helen'], 'sue': 8, 'helen': 10, 'john': 3} Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list