Home > database >  How to get the maximum value of a key in dict?
How to get the maximum value of a key in dict?

Time:04-23

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)

CodePudding user response:

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.....')

CodePudding user response:

This is a slightly simpler version what @Samwise did, in the sense that it's more 'evident', with an explanation of what a lambda maps to, it uses sorted instead of max and no dunder methods, maybe this helps you in understanding how lambda and mapping works and potentially it will help you with Samwise's oneliner :)

videos = {
        'size_476_306': 'https://www.....',
        'size_560_360': 'https://www.....',
        'size_644_414': 'https://www.....',
        'size_720_480': 'https://www.....',
}


multiply = lambda x: (int(x.split('_')[1]) * int(x.split('_')[2]),x)
# this is equivalent to:
# def multiply(x):
#    return int(x.split('_')[1]) * int(x.split('_')[2]),x

key = sorted([*map(multiply, videos.keys())], reverse=False)[0][1]
# this means that you will apply the function multiply to each key in videos 
# the [*something] transforms the mapped list into a list and the sorted function
# sorts the result by the first element of the tuple. The reverse=True means that 
# the result will be sorted in descending order from the highest to the lowest resolution.
# [0] accesses the first element of the sorted list. [1] accesses the
# second element of the tuple. This way, you get the key

print(videos[key])
  • Related