Is there a shorthand for querying a dictionary in python?

Here is the type of request I want to execute, written in pseudocode:

select blob from blobs where blob['color'] == 'red' having maximum(blob['size']) 

Obviously, I could write like this in python:

 redBlobs = []; for blob in blobs: if blob['color'] == 'red': redBlobs.append('blob') largestBlob = None for redBlob in redBlobs: if largestBlob == None or redBlob['size'] > largestBlob['size']: largestBlob = redBlob return largestBlob 

But I suspect there is a cleaner way to do this. I am new to python, so I am still very against it.

EDIT:

Here is a solution I came up with when looking at other questions about SO:

 max([blob for blob in blobs if blob['color'] == 'red'], key = lambda b: b['size']) 

There are supposedly better ways.

+4
source share
4 answers

The following gives the greatest blob

EDIT : catch exception when there is no red blob

 import operator try: largestBlob = max((blob for blob in blobs if blob['color'] == 'red'),key=operator.itemgetter('size')) except ValueError: largestBlob = None 
+10
source

This will complete the task:

 redBlobs = filter(lambda b: b['color'] == 'red', blobs) largestBlob = max(redBlobs, key=lambda b: b['size']) 
+1
source

PiotrLegnica's answer will return the size of the largest blob, not the largest blob. To get the largest blob, use the optional "key" argument for max:

 largestBlob = max((blob for blob in blobs if blob['color'] == 'red'), key=operator.itemgetter('size')) 
+1
source

If I were you, I would use sorting, using size as a key with a generator expression for filetering, getting the first element of this list:

 largestBlob = sorted((blob for blob in blobs if blob['color'] == 'red'), key=lambda x: -x['size'])[0] 
0
source

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


All Articles