Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorthand for querying a dictionary in python?

Here's the type of query I want to execute, written in pseudocode:

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

Obviously, I could write that 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's a cleaner way of doing it. I'm new to python, so I'm still aproaching it very imperatively.

EDIT:

Here's a solution I came up with after looking at some other questions on SO:

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

Presumably, there are better ways.

like image 862
Eric Avatar asked Dec 16 '22 15:12

Eric


1 Answers

The folowing give the largest 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
like image 116
Xavier Combelle Avatar answered Dec 19 '22 04:12

Xavier Combelle