I want to calculate certain statistics over a list of dictionaries which looks something like this:
list1 = [{'hello': "world", 'score': 1.2}, {'hello': "world", 'score': 1.5}, {'hello': "world", 'score': 1.02},
{'hello': "world", 'score': 1.75}]
Specifically, I want to find the min, max, and normalized value of the values associated with score key (meaning I have to update the existing dictionary).
I have implemented it the obvious way which is as follows. However, I was wondering if there is a better way to achieve this?
list1 = [{'hello': "world", 'score': 1.2}, {'hello': "world", 'score': 1.5}, {'hello': "world", 'score': 1.02},
{'hello': "world", 'score': 1.75}]
def min_value(rank_norm):
list_values = []
for x in rank_norm:
list_values.append(x['score'])
return min(list_values)
def max_value(rank_norm):
list_values = []
for x in rank_norm:
list_values.append(x['score'])
return max(list_values)
def normalize_dict(rank_norm, min_val, max_val):
for x in rank_norm:
x['score'] = (x['score']-min_val)/(max_val - min_val)
return rank_norm
min_val_list = min_value(list1)
max_val_list = max_value(list1)
print(min_val_list)
print(max_val_list)
print("Original dict: ", list1)
print("Normalized dict: ", normalize_dict(list1, min_val_list, max_val_list))
I am using Python 3.