简体   繁体   中英

How to find the maximum value of a list within a dictionary

I'm trying to create a dictionary whose values are the maximums between its first element of the lists that are and its second element of the lists that are, I have created this code but it returns the largest between the first list and the second list, and I don't want that.

import numpy as np

dict_pm = {1: [[7560.0, 3346.667], [58440.0, 14653.333]], 
           2: [[460.0, 7500.0], [33460.0, 7500.0]], 
           3: [[3980.0, 1153.333], [12980.0, 10153.333]]}

dict_pm = {key:[np.max(valor[0]),np.max(valor[1]) ] for key, valor in dict_pm.items()}

There can be n lists, in short I want my dictionary to look like this:

Input: dict_pm = {1: [[7560.0, 3346.667], [58440.0, 14653.333]], 2: [[460.0, 7500.0], [33460.0, 7500.0]], 3: [[3980.0, 1153.333], [12980.0, 10153.333]]}

Output: dict_pm = {1: [58440.0, 14653.333], 2: [33460.0, 7500.0], 3: [12980.0, 10153.333]}

My largest list can accommodate more than 2 small lists, in any case the small ones will always have 2 elements but in, the logic would be the same:

Input:
dict_pm = {1: [[7560.0, 3346.667], [58440.0, 14653.333], [40.0, 14.33]], 2: [[460.0, 7500.0], [33460.0, 7500.0], [60.0, 7.0]], 3: [[3980.0, 1153.333], [12980.0, 10153.333], [80.0, 1.33]]}

Output:
dict_pm = {1: [58440.0, 14653.333], 2: [33460.0, 7500.0], 3: [12980.0, 10153.333]}

You can zip the sub-lists of each valor and map them to the max function instead:

{key: list(map(max, zip(*valor))) for key, valor in dict_pm.items()}

You can also use sorted in combination with dict comprehension

In [8]: {k : sorted(v, key=lambda x : (x[0], x[1]))[-1] for k, v in dict_pm.items()}

Out[8]: {1: [58440.0, 14653.333], 2: [33460.0, 7500.0], 3: [12980.0, 10153.333]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM