I have a list of dictionaries and a separate dictionary having the same keys and only the values are different. For example the list of dictionaries look like this:
[{'A': 0.102, 'B': 0.568, 'C': 0.33}, {'A': 0.026, 'B': 0.590, 'C': 0.382}, {'A': 0.005, 'B': 0.857, 'C': 0.137}, {'A': 0.0, 'B': 0.962, 'C': 0.036}, {'A': 0.0, 'B': 0.991, 'C': 0.008}]
and the separate dictionary looks like this:
{'A': 0.005, 'B': 0.956, 'C': 0.038}
I want to compare the separate dictionary with the list of dictionaries and return the index from the list which has higher value than the separate dictionary. In this example, the indices would be 3, 4 as the dictionary in indices 3 and 4 has a higher value for key 'B'
since 'B'
has the highest value in the separate dictionary.
Any ideas on how I should I proceed the problem?
CodePudding user response:
You can use enumerate
for finding index of max value:
org = [
{'A': 0.102, 'B': 0.568, 'C': 0.33},
{'A': 0.026, 'B': 0.590, 'C': 0.382},
{'A': 0.005, 'B': 0.857, 'C': 0.137},
{'A': 0.0, 'B': 0.962, 'C': 0.036},
{'A': 0.0, 'B': 0.991, 'C': 0.008}
]
com = {'A': 0.005, 'B': 0.956, 'C': 0.038}
def fnd_index(org, com):
key_max, val_max = max(com.items(), key=lambda x: x[1])
print('key_max:', key_max)
print('val_max:', val_max)
res = []
for idx, dct in enumerate(org):
if dct[key_max] > val_max:
res.append(idx)
return res
res = fnd_index(org, com)
print('result:', res)
Output:
key_max: B
val_max: 0.956
result: [3, 4]
CodePudding user response:
are you sure that it should be only index 4?
dict_list = [{'A': 0.102, 'B': 0.568, 'C': 0.33},
{'A': 0.026, 'B': 0.590, 'C': 0.382},
{'A': 0.005, 'B': 0.857, 'C': 0.137},
{'A': 0.0, 'B': 0.962, 'C': 0.036},
{'A': 0.0, 'B': 0.991, 'C': 0.008}]
d = {'A': 0.005, 'B': 0.956, 'C': 0.038}
max_val = max(d.values())
idxmax = [i for i,j in enumerate(dict_list) if max(j.values()) > max_val]
print(idxmax) # [3, 4]