Reputation: 33
I would like to get the URL of a video with maximum resolution.
If I had the following dictionary, would it be easiest to get the URL of the video with the maximum size?
Is it best to split the size by partition, format the number into an int type, and then get the value?
videos = {
'size_476_306': 'https://www.....',
'size_560_360': 'https://www.....',
'size_644_414': 'https://www.....',
'size_720_480': 'https://www.....',
}
Solved
I couldn't figure out lambda, so I implemented it in a different way.
for size, v_url in videos.items():
max_size_info = size.split('_')
split_size = int(max_size_info[1])
size_array.append(split_size)
video_array.append(v_url)
max_size = size_array.index(max(size_array))
if str(size_array[max_size]) in v_url:
print(size,v_url)
Upvotes: 1
Views: 73
Reputation: 71562
Is it best to split the size by partition, format the number into an int type, and then get the value?
Yes, that's the way I'd do it:
>>> max(videos.items(), key=lambda i: int.__mul__(*map(int, i[0].split("_")[1:])))
('size_720_480', 'https://www.....')
Here's a slightly more verbose version with a named function:
>>> def get_resolution(key: str) -> int:
... """
... Gets the resolution (as pixel area) from 'size_width_height'.
... e.g. get_resolution("size_720_480") -> 345600
... """
... _, width, height = key.split("_")
... return int(width) * int(height)
...
>>> max(videos, key=get_resolution)
'size_720_480'
Given that expression that gives us the largest key, we can easily get the corresponding value:
>>> videos[max(videos, key=get_resolution)]
'https://www.....'
or we could get the key, value pair by taking the max of items()
, here using a much simpler lambda
that just translates key, value
into get_resolution(key)
:
>>> max(videos.items(), key=lambda i: get_resolution(i[0]))
('size_720_480', 'https://www.....')
Upvotes: 1