'How to extract the Max value within the same key
{'201001': [36, 88, 65, 113, 51, 88, 37, 106, 96, 68, 104, 93],
'201002': [65, 85, 97, 52],
'201003': [85, 63, 86, 52, 71, 53, 51, 48, 52],
'201004': [82, 39, 97, 114, 74, 30, 97],
'201005': [97, 66, 109, 98, 94, 78, 99, 53, 67, 56],
'201006': [116, 98, 39, 69, 33, 84, 62, 39],
'201007': [72, 98, 37],
'201008': [98, 31, 99, 105, 109, 72, 30, 34]}
I have a dictionary looks something like this, and I want to extract the maximum value within the same key. And create a new dictionary with only one max value per key. I have tried the solution provide by Tomerar. But encountered some error, shown below. Does anyone have any idea how to do this? Thanks.
After running the code from Tomerar
[input]
for key,val in dict_all.items():
print(type(val))
[output]
list
[input]
dict_all
{key:max(val) for key,val in dict_all.items()}
[output]
1 dict_all
----> 2 {key:max(val) for key,val in dict_all.items()}
TypeError: '>' not supported between instances of 'str' and 'int'
Solution 1:[1]
dict_t = {
"201001":[1,2,3,4,5],
"201002":[6,7,8,9,1],
"201003":[8,9,10,12],
"201004":[1,20,21,40,100],
}
{key:max(val) for key,val in dict_t.items()}
#output
{'201001': 5, '201002': 9, '201003': 12, '201004': 100}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tomerar |
