Data structure to implement a dictionary with multiple indexes?

后端 未结 3 755
难免孤独
难免孤独 2020-12-09 19:13

I am looking for a data structure that holds the same values under two different indexes, where I can access the data by either one.

Exampl

3条回答
  •  时光取名叫无心
    2020-12-09 19:39

    Just use three maps.

    maps = [dict(), dict(), dict()]
    
    def insert(rec):
       maps[0][rec[0]] = rec
       maps[1][rec[1]] = rec
       maps[2][rec[2]] = rec
    

    Changes to key attributes of the rec object will require reinsertion though. Just like any other map, when you change the key of an object.

    The maps just map key -> object, after all. They don't actually store copies of the object (it just isn't garbage collected). So a map is an index, nothing more. If you want three indexes, use three maps. Write a couple of glue code functions to manage them.

    As mentioned by Trevor, you can also use a shared dictionary:

    index = dict()
    
    def insert(rec):
        index[rec[0]] = rec
        index[rec[1]] = rec
        index[rec[2]] = rec
    

    then you can access it by either.

    Beware of key collisions though!

提交回复
热议问题