I have a dictionary that looks like:
myD={'key_0':[[['descrp_0_0'],Obj_0_0],.....,[['descrp_0_N'],obj_0_N]]
,.....,
'key_N':[[['descrp_N_0'],Obj_N_0],.....,[['descrp_N_N'],obj_N_N]]}
All objs are ndarrays of the same shape and have a function f() that returns an x which is a float i.e.: obj_0_0.f() --> x_0_0
I want to extract a dictionary with the descrp and obj and their respective key where obj.f() (i.e. x) is minimum for the values in each key (at the myD scope of N keys would give N items in shape of [descrp,obj]):
The result must look something like:
resD = {'key_0':[[descrp_0_min],obj_0_min],
.....,
'key_N':[[descrp_N_min],obj_0_min]}
Something like:
minXs = [min([item[-1].f() for item in v]) for k,v in myD.iteritems()]
minObjs = [item for k,v in myD.iteritems() for item in v if item[-1].get_potential_energy() == minXs[myD.keys().index(k)]]
resultList = zip(myD.keys(),minObjs)
resultDict = dict()
for i in resultList:
resultDict[i[0]]=i[1]
Although it works but is rather cumbersome and I think there must be an easier way to do this. Or maybe I should use numpy.ndarray for this purpose?
I appreciate your help and comments.
If I've understood the structure of your data correctly, I think you can solve this with a dictionary comprehension that calls the builtin min function and gives it a key function.
results = {key: min(values, key=lambda x:x[-1].f())
for key, values in myD.iteritems()}
Your code was really close already!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With