根据您的需要,您可以使用简单的遍历:
min(orderedDict.values(), key=lambda x: x.age)
但是,如果您需要 O(1) 的方式来执行此操作,则需要创建自己的类,因为 OrderedDict 仅根据插入顺序对项目进行排序。例如,您可以使用来自Sorted Containers的 SortedDict (或编写您自己的)并执行以下操作(假设您仍然希望能够根据插入顺序获取项目):
from collections import OrderedDict
from sortedcontainers import SortedDict
class MyOrderedDict(OrderedDict):
def __init__(self):
super(MyOrderedDict, self).__init__(self)
self.sorted = SortedDict()
def __setitem__(self, key, value):
super(MyOrderedDict, self).__setitem__(key, value)
self.sorted[value.age] = value
def __delitem__(self, key):
age = super(MyOrderedDict, self).__getitem__(key).age
super(MyOrderedDict, self).__delitem__(key)
self.sorted.__delitem__(age)
def ageIterator(self):
for age in self.sorted:
yield (age, self.sorted[age])
orderedDict = MyOrderedDict()
#...
for item in orderedDict:
# Items in the order of insertions
for age, item in orderedDict.ageIterator():
# Items by age