-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)) 
4
  • 1
    Does this answer your question? Accessing items in an collections.OrderedDict by index Commented Jun 1, 2020 at 9:09
  • 1
    That's what OP did already. Commented Jun 1, 2020 at 9:09
  • Remove list ;) Commented Jun 1, 2020 at 9:09
  • As for Python 3 I think the answer is no Commented Jun 1, 2020 at 9:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.