在字典中找到最接近的匹配数字(python)

时间:2014-03-07 22:15:18

标签: python dictionary numbers match closest

x = 115

freq_chart = {
'C1':'65.4063913251',
'C#1':'69.2956577442',
'D1':'73.4161919794',
'D#1':'77.7817459305',
'E1':'82.4068892282',
'F1':'87.3070578583',
'F#1':'92.4986056779',
'G1':'97.9988589954',
'G#1':'103.826174395',
'A1':'110',
'A#1':'116.5409403795',
'B1':'123.470825314'
}

我需要在freq_chart中返回x最接近的最接近的音符名称。在此示例中,x最接近A#1。语法是什么?谢谢!

1 个答案:

答案 0 :(得分:6)

您可以使用min

>>> min(freq_chart, key=lambda y:abs(float(freq_chart[y])-x))
'A#1'