如何获取字典中具有最高值的键

时间:2021-03-27 09:47:29

标签: python python-3.x

我有一个这样的字典,其中包含随机数作为键和它们的质因数作为值。

d= {123: 2, 43: 1, 54: 2, 12: 2, 76: 2, 84: 3, 98: 2, 678: 3, 543: 2, 231: 3}

我想获得最高值的数字。如果多个键具有相同的值,则应打印出最大的值。 例如,这里的数字 84,678 和 231 都具有最高值,我希望打印出 678 而不是 84 或 231。

2 个答案:

答案 0 :(得分:3)

您可以使用 { this.state.markers.map(marker => ( <MapView.Marker key={marker.id} coordinate={{longitude: marker.longitude, latitude: marker.latitude}}> <MapView.Callout> <View> <View> {marker.imageUri && <Image source = {{uri: marker.imageUri}} style = {{ width: '90%', height: 100, justifyContent: 'center', flex: 1, alignContent: 'center', resizeMode: 'stretch'}} /> } </View> <Text>Lat: {marker.latitude}, Lon: {marker.longitude}</Text> <Text>{marker.email}</Text> </View> </MapView.Callout> </MapView.Marker> )) } 和一个多因素作为比较键,它首先取 max (value) 然后 pair[1] (key)。最后的 pair[0] 是只检索密钥,而不是对

[0]

性能更高的代码 (values = d = {123: 2, 43: 1, 54: 2, 12: 2, 76: 2, 84: 3, 98: 2, 678: 3, 543: 2, 231: 3} max_key = max(values.items(), key=lambda pair: (pair[1], pair[0]))[0] print(max_key) # 678 )

~30%

答案 1 :(得分:0)

d = {123: 2, 43: 1, 54: 2, 12: 2, 76: 2, 84: 3, 98: 2, 678: 3, 543: 2, 231: 3}
#sort values in ascending order
d = dict(sorted(d.items(), key=lambda item: item[1]))
#sort keys in ascending order
d = dict(sorted(d.items()))
#convert it to list of keys and get the last one(max in keys and values)
print(list(d)[-1]) # 678
相关问题