python字典,限定key的范围,找到value最大的对应的key

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29985391/article/details/84588934

一下链接是我在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

猜你喜欢

转载自blog.csdn.net/qq_29985391/article/details/84588934