Dictionary bidirectional

Kless jonas.esp at googlemail.com
Mon Jul 14 08:04:54 EDT 2008


Akathorn Greyhat sent me by email the next solution, which althought
isn't generic it works well:

-------------
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
-------------



More information about the Python-list mailing list