Reputation: 77
I have this list.
dict_list = [{"rp":1,"vi":100},{"rp":2,"vi":70},{"rp":1,"vi":200},{"rp":1,"vi":150},{"rp":2,"vi":300},{"rp":3, "vi":120 }]
I want output as:
[ {"rp":1,"vi":200},{"rp":2,"vi":300},{"rp":3,"vi":120}]
Can anyone help??
Upvotes: 0
Views: 57
Reputation: 42139
You can build a temporary dictionary using the 'rp' values as keys and feeding the data in order of 'vi' value to retain the highest 'vi' value for each unique 'rp' key. Then convert the values of that temporary dictionary into a list of dictionaries:
R = [*{d["rp"]:d for d in sorted(dict_list,key=lambda d:d["vi"])}.values()]
print(R)
[{'rp': 2, 'vi': 300}, {'rp': 1, 'vi': 200}, {'rp': 3, 'vi': 120}]
Upvotes: 2
Reputation: 41
I am not sure if this is the most elegant way to do it but I hope it helps.
you can try to use pandas for something like this:
import pandas as pd
dict_list = [{"rp":1,"vi":100},{"rp":2,"vi":70},{"rp":1,"vi":200},
{"rp":1,"vi":150},{"rp":2,"vi":300},{"rp":3, "vi":120 }]
full = pd.DataFrame(dict_list)
rp_list = pd.Series(full['rp']).unique()
new= []
for rp in rp_list:
values = full.loc[full['rp'] == rp]
max_value = values["vi"].max()
new.append({'rp':rp,'vi':max_value})
print (new)
Upvotes: 0
Reputation: 9600
One solution could be to create a dictionary with key as the rp
value and value as the maximum vi
value.
Use the created dictionary to create the required list
dict_list = [{"rp":1,"vi":100},{"rp":2,"vi":70},{"rp":1,"vi":200},{"rp":1,"vi":150},{"rp":2,"vi":300},{"rp":3, "vi":120 }]
res = dict()
for elt in dict_list:
res[elt["rp"]] = max(res.get(elt["rp"], 0), elt["vi"]) # overwrite with max for matching keys
dict_list = [{"rp": key, "vi": value} for key, value in res.items()]
print(dict_list)
Upvotes: 1