Dictionary bidirectional

Akathorn Greyhat akathorn at gmail.com
Mon Jul 14 10:01:07 EDT 2008


This is a better version of the class that I sen't you, now it raises a
KeyError when you try to insert a value that is already in

############################
class MyCoolDictionary(dict):
    def __init__(self, *args, **kargs):
        dict.__init__(self, *args, **kargs)

    def __setitem__(self, *args, **kargs):
        for i in dictio.values():
            if args[0]==i or args[1]==i:
                raise KeyError, 'Value already exists'

        dict.__setitem__(self, *args, **kargs)

    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)

        except KeyError:
            keys=[]
            for i in dictio.keys():
                if dictio[i]==item:
                    keys.append(i)
            if not keys:
                raise KeyError, 'Can\'t found key or value "' + str(item) +
'"'
            return keys
############################

Feel free to change anything you want or need

Regards,
Akathorn Greyhat


2008/7/14 Kless <jonas.esp at googlemail.com>:

> I need a dictionary where get the result from a 'key' (on left), but
> also from a 'value' (on right), how to get it?
>
> I know that dictionaries aren't bidirectional, but is there any way
> without use two dictionaries?
>
>
> Thanks in advance!
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080714/2814e56e/attachment-0001.html>


More information about the Python-list mailing list