1. 程式人生 > >python字典,限定key的範圍,找到value最大的對應的key

python字典,限定key的範圍,找到value最大的對應的key

一下連結是我在stack overflow上的提問及解答,

https://stackoverflow.com/questions/53513792/python-dictionary-find-key-of-max-vlue/53515710#53515710

如對於字典d = {1:5, 2:0, 3:4, 4:0, 5:1}, 限定範圍k in [1, 2, 3] 或{1, 2, 3}正確解法如下:

Just get the keys and values for the keys 1, 2 and 3 in a list of tuples, sort the list and get the first tuple element [0]

 key [0].

d = {1: 5, 2: 0, 3: 4, 4: 0, 5: 1}
key_max_val = sorted([(k,v) for k,v in d.items() if k in [1,2,3]])[0][0]
print(key_max_val) # Outputs 1