-1

Is there a way to implement an equivalent of the item method shown below, which gives the same functionality without copying all the data or looping? So in this example it would return ('bar', 20).

from collections import OrderedDict

class MyOrderedDict(OrderedDict):

    def item(self, index):
        return list(self.items())[index]


d = MyOrderedDict()
d["foo"] = 10
d["bar"] = 20
d["baz"] = 25

print(d.item(1))
alani
  • 12,573
  • 2
  • 13
  • 23

1 Answers1

1

You can try

from collections import OrderedDict

class MyOrderedDict(OrderedDict):
    name_to_index = {}
    def item(self, index):
        return tuple([self.name_to_index[index], self[self.name_to_index[index]]])

    def __setitem__(self, key, value):
        self.name_to_index[len(self.name_to_index)] = key
        super().__setitem__(key, value)


d = MyOrderedDict()
d["foo"] = 10
d["bar"] = 20
d["baz"] = 25

print(d.item(1))

Output

('bar', 20)

This code will store in each assignment of value the index and the key and when you will call item with an index it will return the relevant value for the index position.

Leo Arad
  • 4,452
  • 2
  • 6
  • 17
  • Thank you. On reflection, unfortunately I have probably not helped the question by framing it in terms of my own subclass, because really it is about how to extract items from _any_ instances of the existing OrderedDict class, rather than relying on methods such as `__setitem__` having been overridden when populating the dictionary. Apologies for that. I don't want to destroy your answer by editing the question now, but the use case I probably more had in mind was some function like `def item(dct, index): ...` outside the class. – alani Jun 01 '20 at 09:43