Data structure to implement a dictionary with multiple indexes?

后端 未结 3 757
难免孤独
难免孤独 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:36

    Is there a particular reason you can't just use a dictionary:

    x = {}
    x[1] = x['karl'] = dog
    x[2] = x['lisa'] = cat
    

    Then you can access it by either.

    If you really don't want to repeat your self you do this:

    class MysticalDataStructure(dict):
        def add(self, key1, key2, value):
            return self[key1] = self[key2] = value
    
    x = MysticalDataStructure()
    x.add(1, 'karl', dog)
    x.add(2, 'lisa', cat)
    

提交回复
热议问题