Dictionary bidirectional

Akathorn Greyhat akathorn at gmail.com
Sun Jul 13 22:28:39 EDT 2008


---------- Forwarded message ----------
From: Akathorn Greyhat <akathorn at gmail.com>
Date: 2008/7/14
Subject: Re: Dictionary bidirectional
To: Kless <jonas.esp at googlemail.com>




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
>


You could make your own class for that, maybe something like


#########

class MyCoolDictionary(dict):
    def __init__(self, *args, **kargs):
        dict.__init__(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)
            return keys

dictio=MyCoolDictionary({"a" : 1, "b" : 2, "c" : 2})
print dictio["a"]
print dictio["b"]
print dictio[1]
print dictio[2]
#########

The output of this code is:
1
2
['a']
['c', 'b']

Note that it isn't finish, maybe you'll need to make some kind of test
before adding a new value because with this code one value can have multiple
keys, and I have fixed it by returning a list of keys instead a single
value. It's up to you =)

I'm sorry of my poor english =(

Regards,
Akathorn Greyhat
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080714/86b2114e/attachment-0001.html>


More information about the Python-list mailing list