获取字典中每个键的最大值 python
Getting the max value for each key in a dictionary python
我有以下字典,我想输出每个键的最大值:
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]
使用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}
万一字典有任何键的空列表,你可以在字典压缩中对长度进行安全检查以消除对
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}
我有以下字典,我想输出每个键的最大值:
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]
使用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}
万一字典有任何键的空列表,你可以在字典压缩中对长度进行安全检查以消除对
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}