获取字典python中每个键的最大值

时间:2021-07-01 15:40:49

标签: python python-3.x list dictionary key

我有以下字典,我想输出每个键的最大值:

yo = {'is': [1, 3, 4, 8, 10],
             'at': [3, 10, 15, 7, 9],
             'test': [5, 3, 7, 8, 1],
             'this': [2, 3, 5, 6, 11]}

例如,输出应该是这样的

[10, 15, 8, 11]
or 
['is' 10, 'at' 15, 'test' 8, 'this' 11]

2 个答案:

答案 0 :(得分:6)

使用list comprehension

result = [max(v) for k,v in yo.items()]
# PRINTS [10, 15, 8, 11]

dict comprehension

result_dict = {k:max(v) for k,v in yo.items()}
# Prints {'is': 10, 'at': 15, 'test': 8, 'this': 11}

答案 1 :(得分:0)

如果dict有任何键的空列表,您可以在dict压缩中对长度进行安全检查以消除对

result = [max(v) for v in yo.values() if len(v)>0]
result_dict = {k:max(v) for k,v in yo.items() if len(v)>0}