Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove duplicate keys in dictionary/JSON object from list by keep the highest number

I have a list of dictionaries:

te = [
  {
    "Name": "Bala",
    "price": 1
  },
  {
    "Name": "Bala",
    "price": 2
  },
  {
    "Name": "Bala",
    "price": 6
  },
  {
    "Name": "Bala",
    "price": 4
  },
  {
      "Name": "Bala1",
      "price": "None"
  }     ]

I would like to remove the duplicates from the "Name" by keeping the maximum from price fields.

I tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

unique = { each['Name'] : each for each in te }.values()

The results is on the last name ‘Bala’ which is price is 4.

[{'Name': 'Bala', 'price': 4 }, {'Name': 'Bala1', 'price': 'None' }]

What I expect:

[{'Name': 'Bala', 'price': 6 }, {'Name': 'Bala1', 'price': 'None' }]

>Solution :

because its returns unique ones from duplicated fields in your array, not with maximum price …

you can use this part of the code to get what you are expected:

unique_max_values = []
for idx, item in enumerate(te):
    if [value["Name"] for value in unique_max_values if value["Name"] == item["Name"]]:
        idx = [i for i, v in enumerate(unique_max_values) if v["Name"] == item["Name"]]
        unique_max_values[idx[0]] = item if item["price"] > unique_max_values[idx[0]]["price"] else unique_max_values[
            idx[0]]
    else:
        unique_max_values.append(item)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading