简体   繁体   中英

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'.

in above example it should print

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM