Python - select a dictionary from a list that is closer to the global value

I have a list of image resolution dictionaries:

[
{'ratio': 1.7777777777777777, 'pixels': 230400, 'key': 'hor_640x360'}, 
{'ratio': 2.1006711409395975, 'pixels': 46637, 'key': 'hor_313x149'}, 
{'ratio': 2.1006711409395975, 'pixels': 746192, 'key': 'hor_1252x596'}
]

I need to select a dictionary whose relation is closer to 1.77672955975(that is, the result float(565) / float(318)), and if the ratio is equal, then with the largest number of pixels. In other words, I need to select the largest image from the list, which after resizing and cropping to 565x318 will require less cropping.

I thought about sorting the list 2 times, the first time based on pixels, and the second based on a smaller result abs(ratio - (float(565) / float(318))). Thus, the one with the largest number of pixels and the closest match will remain on top. But how to do sorting?

+4
source share
2 answers

You can use min(..)for it with key:

matching_dic = min(dicts,key=lambda x:(abs(1.77672955975-x['ratio']),-x['pixels']))

as a result of:

>>> min(dicts,key=lambda x:(abs(1.77672955975-x['ratio']),-x['pixels']))
{'key': 'hor_640x360', 'pixels': 230400, 'ratio': 1.7777777777777777}

The idea is that key: lambda x:(abs(1.77672955975-x['ratio']),-x['pixels'])for each dictionary , it will calculate the difference between your given ratio (here 1.77672955975) and 'ratio'this dictionary. We return a tuple (with -x['pixels']as the second element for tai-breaking (kudos to @MosesKoledoye to determine this).

+2
source

The standard solution for sorting by multiple attributes is to use tuples, because tuples are sorted by their elements.

keyfunc= lambda r:(abs(r['ratio']-1.77672955975), -r['pixels'])
print(min(resolutions, key=keyfunc))
+2
source

Source: https://habr.com/ru/post/1670765/


All Articles