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?





is this an orderedDict or List? code shows list.
– vinay
Sep 4 at 2:45





@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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)