I have an orderedDict of objects,
[<f.Packet object at 0x07AD7090>, <f.Packet object at 0x07ACA8F0>, <f.Packet object at 0x07ACAC90>, <f.Packet object at 0x07A5F5D0>, <f.Packet object at 0x07ACA410>, <f.Packet object at 0x07ABBF50>, <f.Packet object at 0x07ACA830>]
Each of these objects has attributes such as name, age, and source. How can I get the object which its age is the minimum one?
Depending on what you need, you might use simple traversal:
min(orderedDict.values(), key=lambda x: x.age)
But if you need a O(1) way to do it, you need to create your own class, because OrderedDict orders items only based on the insertion order. For example, you can use SortedDict from Sorted Containers (or write your own) and do something like this (assuming you still want to be able to get items based on the insertion order):
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