在嵌套字典Python中查找最接近的值

在嵌套字典Python中查找最接近的值,python,dictionary,nested,nearest-neighbor,closest,Python,Dictionary,Nested,Nearest Neighbor,Closest,假设嵌套字典如上所示。需要找到最接近targetModules=4.37的模量值,然后打印“cat” 在上面的示例中,它应该打印 targetcat=[1,2,3] 对于这个示例,使用列表和数组很简单,但实际上不知道从何处开始。假设您的数据模式是可靠的。然后试试这个: a={'alpha': {'modulus': [5], 'cat': [1, 2, 3]}, 'beta': {'modulus': [7], 'cat': [5, 6, 9]}, 'gamma': {'modulus

假设嵌套字典如上所示。需要找到最接近targetModules=4.37的模量值,然后打印“cat”

在上面的示例中,它应该打印

targetcat=[1,2,3]


对于这个示例,使用列表和数组很简单,但实际上不知道从何处开始。

假设您的数据模式是可靠的。然后试试这个:

    a={'alpha': {'modulus': [5], 'cat': [1, 2, 3]}, 'beta': {'modulus': [7], 'cat': [5, 6, 9]}, 
'gamma': {'modulus': [1], 'cat': [0, 0, 1]}}
a={'alpha': {'modulus': [5], 'cat': [1, 2, 3]}, 'beta': {'modulus': [7], 'cat': [5, 6, 9]}, 
'gamma': {'modulus': [1], 'cat': [0, 0, 1]}}
target = 4.37

#first, decide what you mean by close
def distance(x, y):
    return abs(x[0]-y[0])

#use your distance measure to get the closest
best = min(a, key=lambda x: distance(a[x]['modulus'],[target]))

#print your target answer
print "targetcat = {}".format(a[best]['cat'])

使用列表理解来迭代数据中的每条记录,然后生成模差、cat list的元组。找到最小元组后,该元组的第二个元素(cat列表)就是答案。

谢谢!完美地工作
a={'alpha': {'modulus': [5], 'cat': [1, 2, 3]}, 'beta': {'modulus': [7], 'cat': [5, 6, 9]}, 
'gamma': {'modulus': [1], 'cat': [0, 0, 1]}}
target = 4.37

#first, decide what you mean by close
def distance(x, y):
    return abs(x[0]-y[0])

#use your distance measure to get the closest
best = min(a, key=lambda x: distance(a[x]['modulus'],[target]))

#print your target answer
print "targetcat = {}".format(a[best]['cat'])
def closest(data, target):
    return min((abs(record['modulus'][0] - target), record['cat']) for record in data.values())[1]

closest(a, 4.75)
# [1, 2, 3]