Reputation: 12608
I have a python3 nested dictionary that looks like this.
myArray = {0: {
'valueset1' : {
'val1' : 345,
'val2' : 56,
},
'success' : True},
},
{1: {
'valueset1' : {
'val1' : 145,
'val2' : 156,
},
'success' : True},
},
{2: {
'valueset1' : {
'val1' : 35,
'val2' : 6,
},
'success' : True},
}
I am trying to return the index of the entry with the lowest valueset1.val1 - so in the instance above it would return 2
I have this so far...
x = min(myArray['valueset1']['val1'])
I think it is not working because I am not iterating through the dictionary, whre am I going wrong?
Upvotes: 0
Views: 683
Reputation: 71461
To handle structures of unknown depth, you can use recursion to flatten the dictionary:
myArray = {0: {'success': True, 'valueset1': {'val2': 56, 'val1': 345}}, 1: {'success': True, 'valueset1': {'val2': 156, 'val1': 145}}, 2: {'success': True, 'valueset1': {'val2': 6, 'val1': 35}}}
def get_l(d):
return [c for b in d.values() for c in ([b] if isinstance(b, int) else get_l(b))]
d = {a:list(filter(lambda x:not isinstance(x, bool), get_l(b))) for a, b in myArray.items()}
final_result = min(d, key=lambda x:min(d[x]))
Output:
2
Upvotes: 0
Reputation: 837
Your nested dictionary is wrong, I have modified it AND code to get minimum value is written below:-
myArray = { 0: {
'valueset1' : {
'val1' : 345,
'val2' : 56,},
'success' : True},
1: {
'valueset1' : {
'val1' : 145,
'val2' : 156,},
'success' : True},
2: {
'valueset1' : {
'val1' : 35,
'val2' : 6,},
'success' : True},
}
import numpy as np
new_list = np.array([])
new_key = np.array([])
for var in myArray:
new_list = np.append( new_list ,myArray[var]['valueset1']['val1'] )
new_key = np.append(new_key, var)
index = new_list.argmin() # It will give indexing value of a minimum value.
new_key[index]
OutPut
2
I hope it may help you
Upvotes: 2
Reputation: 8709
Here, myArray
is not a dict
, but a tuple
of dict type elements.
You can try this:
myArray = {0: {
'valueset1' : {
'val1' : 345,
'val2' : 56,
},
'success' : True},
},{1: {
'valueset1' : {
'val1' : 145,
'val2' : 156,
},
'success' : True},
},{2: {
'valueset1' : {
'val1' : 35,
'val2' : 6,
},
'success' : True},
}
val = [] # Here, val is a list of tuples (index, value)
for i in range(len(myArray)):
val.append((i, myArray[i][i]['valueset1']['val1']))
val.sort(key=lambda x: x[1]) # sort the list "val" in ascending order based on value
print('Index of minimum value in dictionary is {}'.format(val[0][0]))
output:
Index of minimum value in dictionary is 2
Upvotes: 0
Reputation: 84
This should make the trick:
array_val1 = [x[i]['valueset1']['val1'] for i,x in enumerate(myArray)]
array_val1.index(min(array_val1))
You forgot the brackets [] on your array definition :)
Upvotes: 3