Given your limitations, anyone trying to implement what you are looking for with a dict will bark the wrong tree. Instead, you should write a subclass of list that overrides __getitem__ to provide the desired behavior. I wrote it so that he first tried to get the desired element by index, and then returned to searching for the element using the key attribute of the contained objects. (This may be a property if the object should determine this dynamically.)
The linear search cannot be avoided unless you want to duplicate something; I am sure that the C # implementation does the same if you do not permit the use of a dictionary to store keys.
class KeyedCollection(list): def __getitem__(self, key): if isinstance(key, int) or isinstance(key, slice): return list.__getitem__(key) for item in self: if getattr(item, "key", 0) == key: return item raise KeyError('item with key `%s` not found' % key)
You might also want to override __contains__ similar way so that you can say if "key" in kc... If you want to make it even more like a dict , you can also implement keys() and so on. They will be equally inefficient, but you will have an API like a dict that also works like a list.
source share