Reputation:
So, I need to build a filter that basically takes the following information...
dictlist = [{'ext': 'mp4',
'height': 480,
'id', 'pies'},
{'ext': 'webm',
'height': 360,
'id', 'pies2'},
{'ext': 'mp4',
'height': 360,
'id', 'charles1'},
{'ext': 'mp4',
'height': 720,
'id', 'tucker'}]
(there's more stuff there, but this is simplified)
And then outputs the id of the element that is both an mp4 (or whatever I want. I'm aiming for a function or, alternative, to use built-in stuff to be more python-y if it exists) and has the highest height below a value.
For example, I'd like to build a function that is similar to...
def getmestuff(listofdics, extrequired, heightmax):
/*do the work*/
return id;
So for example using the above data...
getmestuff(dictlist, 'mp4', 720)
Would return... pies
Upvotes: 1
Views: 8144
Reputation: 309919
how about this:
mp4s = (d for d in dictlist if d['ext'] == 'mp4')
max(mp4s, key=lambda x: x['height'])
This will return the "max" dictionary -- From there getting the id
is easy. (and you could easily inline the mp4s
, but I've broken it into 2 lines for clarity.)
A little less easy to read, but more compact:
max(dictlist, key=lambda d: (d['ext'] == 'mp4', d['height']))
The first version will also helpfully raise a ValueError
if there are no mp4's in the list whereas the second version will just return the thing with the biggest height in that case.
Upvotes: 6
Reputation: 180401
A function to do the same:
def get_me_stuff(dict_l, val, max_h):
best = 0
id = None
for d in dict_l:
h = d.get('height')
if d.get("ext") == val and max_h > h > best:
best = h
id = d.get("id")
return id
Upvotes: 0