[英]Find closest value in nested dictionary Python
a={'alpha': {'modulus': [5], 'cat': [1, 2, 3]}, 'beta': {'modulus': [7], 'cat': [5, 6, 9]},
'gamma': {'modulus': [1], 'cat': [0, 0, 1]}}
Suppose a nested dictionary is as given above. 假设嵌套字典如上所述。 Need to find the value of modulus closest to lets say
targetmodulus=4.37
and then print 'cat'. 需要找到最接近的模数值,例如
targetmodulus=4.37
,然后打印“ cat”。
in above example it should print 在上面的示例中,它应该打印
targetcat=[1,2,3] targetcat = [1,2,3]
With list and arrays its straightforward but really don't know where to start for this example. 使用列表和数组很简单,但实际上不知道该示例从哪里开始。
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
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'])
Suppose that your data schema is solid. 假设您的数据架构是可靠的。 Then try this:
然后试试这个:
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]
use list comprehension to iterate each record in the data, then make a tuple of (modulus diff, cat list). 使用列表推导迭代数据中的每个记录,然后创建一个元组(模数差异,目录)。 When you find the minimal tuple, then the second element of that tuple - which is the cat list - is the answer.
当找到最小的元组时,答案就是该元组的第二个元素-猫列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.