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

时间:2015-03-24 10:59:59

标签: python dictionary nested nearest-neighbor closest

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

假设嵌套字典如上所述。需要找到最接近模数的值,比如说targetmodulus=4.37,然后打印“猫”。

在上面的示例中应该打印

targetcat = [1,2,3]

列表和数组很简单,但实际上并不知道从这个例子开始。

3 个答案:

答案 0 :(得分:0)

def findValue(dictionary,targetmodulus):   
    diff = None
    item = None
    for  y in dictionary:
        x = dictionary[y]
        difference= abs(targetmodulus - x['modulus'][0])
        if(diff == None or difference < diff):
            diff = difference
            item = x['cat']
    return item

答案 1 :(得分:0)

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'])

答案 2 :(得分:0)

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

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]

使用list comprehension迭代数据中的每个记录,然后创建一个(模数diff,cat list)元组。当你找到最小元组时,那个元组的第二个元素 - 即猫列表 - 就是答案。