简体   繁体   中英

Find closest item in a sorted List of Dictionaries

I have a list of dictionaries, which are sorted on one property:

[{"name":"efi", "sortedProp":"01df"},
 {"name":"abe", "sortedProp":"1de9"},
 {"name":"bit", "sortedProp":"e182"}...]

I want to find the closest value of sortedProp to a given value (say for example 1dff should return the second dict here). I know I can use bisect for this for optimal speed (performance is important, since the list is ~30,000 dicts long), and I've found answers for finding exact values in a list of dicts , and finding closest value in a list of ints , but I can't seem to find an answer for finding the closest value in a list of dicts.

edit: I'm not asking how to sort the list of dicts, I already have done that. I'm asking how to find the dict that contains the closest value of sortedProp to a given value.

edit2: I'm using hexadecimal numbers (results from a phash run) as the sorted property, so 'closest' is defined as the Hamming distance between the two hashes.

def takeClosestEx(myList, myNumber):
    """
    Assumes myList is not sorted. Returns closest value to myNumber.
    """

    return min(myList, key=lambda x:abs(int(x["sortedProp"], 16)-myNumber))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM