Sunil K Behera
Sunil K Behera

Reputation: 77

get maximum valued dictionary from list of dictionaries in python

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

Answers (3)

Alain T.
Alain T.

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

Salman Hammad
Salman Hammad

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

Krishna Chaurasia
Krishna Chaurasia

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

Related Questions