how get the object which has the minimum value in an orderedDict?
how get the object which has the minimum value in an orderedDict?
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?
@vinay: the type is <class 'collections.OrderedDict'>
– Elham
Sep 4 at 2:47
2 Answers
2
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
try this once, suppose you have d as orderedDict
import operator
#...
person=sorted(d.values(), key=operator.attrgetter('age'))[0]
print person.age
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
is this an orderedDict or List? code shows list.
– vinay
Sep 4 at 2:45