Search code examples
pythondictionaryordereddictionary

Finding the lowest value of an item in a list of OrderedDict


I have an OrderedDict that each key has more than one value.

list_of_dict = 
[OrderedDict([('time', 0.18), ('dist', 92.61), ('x', True)]), 
 OrderedDict([('time', 0.92), ('dist', 92.10), ('x', True)]),
 OrderedDict([('time', 1.45), ('dist', 92.79), ('x', False)])]

Need to return the dictionary with lowest time among all the orderededDict present in the list_of_dict.

Example - list_of_dict[0][time] is lowest among remaining dict, so need to return entire

OrderedDict([('time', 0.18), ('dist', 92.61), ('x', True)])

Solution

  • Just use the min() function with key as a lambda.

    from collections import OrderedDict
    
    list_of_dict = [
        OrderedDict([("time", 1.45), ("dist", 92.79), ("x", False)]),
        OrderedDict([("time", 0.18), ("dist", 92.61), ("x", True)]),
        OrderedDict([("time", 0.92), ("dist", 92.10), ("x", True)]),
    ]
    
    print(min(list_of_dict, key=lambda x: x["time"]))
    

    You can also use itemgetter, instead of a lambda.

    from collections import OrderedDict
    from operator import itemgetter
    
    list_of_dict = [
        OrderedDict([("time", 1.45), ("dist", 92.79), ("x", False)]),
        OrderedDict([("time", 0.18), ("dist", 92.61), ("x", True)]),
        OrderedDict([("time", 0.92), ("dist", 92.10), ("x", True)]),
    ]
    
    print(min(list_of_dict, key=itemgetter("time")))