简体   繁体   中英

Getting the max value for each key in a dictionary python

I have the following dictionary and I would like to output the max value for each 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]}

For example, the output should look something like this

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

Use list comprehension :

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

OR dict comprehension :

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

In case if dict has empty list for any key, you can do safe check on length in dict compression to eliminate the pair

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}

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