Welcome, guest | Sign In | My Account | Store | Cart

Sometimes it is useful to be able to see fetch all keys in a dictionary which have a common value. The LookupDict class can do this.

Other times, when a 1 to 1 mapping of keys and values, and values to keys is needed, the ReverseDict class could be used.

Python, 37 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class ReverseDict(dict):
    """
    A dictionary which can lookup values by key, and keys by value.
    All values and keys must be hashable, and unique.
    """
    def __init__(self, *args, **kw):
        dict.__init__(self, *args, **kw)
        self.reverse = dict((reversed(list(i)) for i in self.items()))

    def __setitem__(self, key, value):
        dict.__setitem__(self, key, value)
        self.reverse[value] = key


class LookupDict(dict):
    """
    A dictionary which can lookup values by key, and keys by value.
    The lookup method returns a list of keys with matching values
    to the value argument.
    """
    def __init__(self, *args, **kw):
        dict.__init__(self, *args, **kw)

    def lookup(self, value):
        return [item[0] for item in self.items() if item[1] == value]


if __name__ == "__main__":
    a = ReverseDict(((1,2),(3,4)))
    print a[1]
    print a.reverse[2]
    a["123"] = 67
    print a["123"]
    print a.reverse[67]
    print "-" * 20
    b = LookupDict(((1,2),(3,4),(4,2)))
    print b.lookup(2)

The ReverseDict class must have unique values and keys, and all values and keys must be hashable.

Created by S W on Thu, 2 Jun 2005 (PSF)
Python recipes (4591)
S W's recipes (20)

Required Modules

  • (none specified)

Other Information and Tasks