python:从OrderedDict通过数字索引获取项目的有效方法
是否有一种方法可以实现如下所示的python:从OrderedDict通过数字索引获取项目的有效方法,python,ordereddictionary,Python,Ordereddictionary,是否有一种方法可以实现如下所示的项方法的等效方法,该方法在不复制所有数据或循环的情况下提供相同的功能?因此在本例中,它将返回('bar',20) 你可以试试 from collections import OrderedDict class MyOrderedDict(OrderedDict): name_to_index = {} def item(self, index): return tuple([self.name_to_index[index], s
项
方法的等效方法,该方法在不复制所有数据或循环的情况下提供相同的功能?因此在本例中,它将返回('bar',20)
你可以试试
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))
输出
('bar', 20)
此代码将在每个赋值中存储索引和键,当您使用索引调用项时,它将返回索引位置的相关值。这是否回答了您的问题?OP已经这么做了。删除
列表;)至于Python 3,我认为答案是否定的。反省一下,不幸的是,我可能没有用我自己的子类来构建这个问题,因为它实际上是关于如何从现有OrderedDict类的任何实例中提取项的,而不是依赖于在填充字典时被重写的方法,例如\uuuuuuu setitem\uuuuu
。对此表示歉意。我不想现在就编辑这个问题来破坏你的答案,但是我可能更想知道的用例是一些函数,比如def item(dct,index):…
类外函数。
('bar', 20)