Python: Finding a key of dictionary element with the max/ min value
Quite a simple question that can be solved in several ways:
1
2
3
4
5
6
7
8
9
| __author__ = 'swayam' my_dict = { 'a' : 2 , 'b' : 5 , 'c' : 3 , 'd' : 8 , 'e' : 3 } maxValKey = max (my_dict, key = my_dict.get) >>> d minValKey = min (my_dict, key = my_dict.get) >>> b |
What if you need (key, value) pair:
1
2
3
4
5
6
7
8
9
| __author__ = 'swayam' from operator import itemgetter maxPair = max (my_dict.iteritems(), key = itemgetter( 1 )) >>> ( 'd' , 18 ) minPair = min (my_dict.iteritems(), key = itemgetter( 1 )) >>> ( 'b' , 1 ) |
But what if you have several equal smallest or largest values in your dict and you need all of them:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| __author__ = 'swayam' my_dict = { 'a' : 2 , 'b' : 1 , 'c' : 6 , 'd' : 18 , 'e' : 13 , 'f' : 1 , 'g' : 18 } vals = my_dict.values() maxVal, minVal = max (vals), min (vals) minVals, maxVals = [], [] for k in my_dict.iterkeys(): if my_dict[k] = = maxVal: maxVals.append((k, maxVal)) elif my_dict[k] = = minVal: minVals.append((k, minVal)) >>> [( 'd' , 18 ), ( 'g' , 18 )] >>> [( 'b' , 1 ), ( 'f' , 1 )] |
Below are more options to do the same:
1
2
3
4
5
6
| __author__ = 'swayam' min_value = min (my_dict.values()) max_value = max (my_dict.values()) min_result = [(key, value) for key, value in my_dict.iteritems() if value = = min_value] max_result = [(key, value) for key, value in my_dict.iteritems() if value = = max_value ] |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| __author__ = 'swayam' from collections import defaultdict from operator import itemgetter my_dict = { 'a' : 2 , 'b' : 1 , 'c' : 6 , 'd' : 18 , 'e' : 13 , 'f' : 1 , 'g' : 18 } def get_res(dVals): res = defaultdict( list ) for k, v in dVals.items(): res[v].append(k) return min (res.items(), key = itemgetter( 0 )), max (res.items(), key = itemgetter( 0 )) print get_res(my_dict) >>> (( 1 , [ 'f' , 'b' ]), ( 18 , [ 'g' , 'd' ])) |
Comments
Post a Comment